我正在尝试将顶部的代码块抽象出来,使其看起来像底部的代码块。

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 有点陌生。任何指导我的见解将不胜感激:)

请您参考如下方法:

有很多方法可以做到这一点。您没有显示足够的上下文来缩小确切的最佳解决方案是您正在做的事情,但鉴于那里有什么,我可以展示一些可能有帮助的东西。

如果您想使用标准查询,那么而不是像这样......

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() 
} 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!