如何将隐式参数传递给Grails中的Closure?

时间:2019-04-27 17:30:23

标签: grails groovy closures gorm

我有许多具有相同逻辑的查询,因此我决定将其提取为闭包。

这里是一个例子:

Closure whereByProjectIdAndUser = { Criteria cr, Long projectId, User user ->
    Long userId = user.id
    Boolean isReviewer = user.isReviewer()

    cr.isNull 'project.deletedAt'
    cr.eq 'project.id', projectId

    (cr | {
        cr.eq 'owner.id', userId

        if (isReviewer) {
            cr & {
                cr.eq 'reviewer.id', userId
                cr.ne 'project.certificationStatus', ProjectCertificationStatus.None
            }
        }
    })
}

@Transactional(readOnly = true)
RrmUtilization[] getAllByProjectIdAndUser(Long projectId, User user) {

    BuildableCriteria cr = RrmUtilization.createCriteria()
    RrmUtilization[] result = cr.list {
        createAlias('project', 'project', JoinType.INNER_JOIN)
        createAlias('project.owner', 'owner', JoinType.INNER_JOIN)
        createAlias('project.reviewer', 'reviewer', JoinType.LEFT_OUTER_JOIN)

        isNull 'deletedAt'

        whereByProjectIdAndUser(cr, projectId, user)

    } as RrmUtilization[]

    result
}

这很好,但是,我试图了解如何避免将BuildableCriteria显式传递给闭包?有没有办法让它隐式传递并获得更好的代码?

也许总体上有一些更好的方法?

1 个答案:

答案 0 :(得分:0)

您可以使用关键字this来访问闭包的封闭类中的参数。

Groovy文档:http://groovy-lang.org/closures.html#closure-owner