我有很多具有相同逻辑的查询,我决定将其提取到闭包中。
下面是一个示例:
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
}
这工作得很好,但是,我试图了解如何避免将可构建标准显式传递到闭包中?有没有办法让它隐式传递并获得更好的代码?
也许总的来说有一些更好的方法?
可以使用关键字 this
来访问闭包的封闭类中的参数。
时髦的文档:http://groovy-lang.org/closures.html#closure-owner