我试图将这个顶级代码块抽象出来,看起来像是底层的代码块。
if (params.xId) {
and {
'in'(aggregateClassReference, hierarchy['x'])
eq(aggregateIdReference, params.xId as Long)
}
}
if (params.yId) {
and {
'in'(aggregateReference, hierarchy['y'])
eq(aggregateIdReference, params.yId as Long)
}
}
...
if (params.xId) { belongsToHierarchy('x', params.xId as Long) }
if (params.yId) { belongsToHierarchy('y', params.yId as Long) }
我使用gorm条件查询,但我不想要这些大块代码。有没有办法在自定义函数中返回这些条件查询的闭包?现在的问题是我把下面的代码放在
中def criteria = DetachedCriteria.build(...)
之后我做了
criteria.list(...)
执行。以某种方式返回
的闭包很棒 and {
'in'{...}
eq {...}
}
在构建中的自定义函数中,但我还没有能够解决这个问题。有点新鲜的grails。我将非常感谢任何指导我的见解:)
答案 0 :(得分:1)
有很多方法可以解决这个问题。你没有展示足够的背景来缩小最佳解决方案是你正在做什么,但鉴于有什么,我可以展示可能有帮助的事情。
如果你想使用条件查询,而不是像这样......
def results = SomeDomainClass.withCriteria {
if (params.xId) {
and {
'in'(aggregateClassReference, hierarchy['x'])
eq(aggregateIdReference, params.xId as Long)
}
}
if (params.yId) {
and {
'in'(aggregateReference, hierarchy['y'])
eq(aggregateIdReference, params.yId as Long)
}
}
}
你可以这样做......
def results = SomeDomainClass.withCriteria {
if (params.xId) {
belongsToHierarchy 'x', params.long('xId'), delegate
}
if (params.yId) {
belongsToHierarchy 'y', params.long('yId'), delegate
}
}
// ...
// it isn't clear from your example if
// aggregateClassReference and hierarchy are local
// variables in the context where the criteria
// query is being initialized or if they are
// instance variables. If they are instance variables
// the code below will work. If they are local
// variables then they might need to be passed as
// arguments into this belongsToHierarchy method...
void belongsToHierarchy(String arg, long id, delegate) {
def query = {
// not sure why you had the "and" in your example, but
// I will leave it here assuming there is a reason...
and {
'in' aggregateClassReference, hierarchy[arg]
eq aggregateIdReference, id
}
}
query.delegate = delegate
query()
}