2017-10-17 65 views
0

我想抽象出这个顶部的代码块看起来像底部的代码块。如何创建一个返回grails标准方法的闭包的自定义函数

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

执行。在某种程度上返回一个封闭的结构,但是我还没有弄清楚这个问题。 Grails有点新鲜。任何洞察力指导我将不胜感激:)

+1

也许命名查询可以帮助?你看过他们吗? http://docs.grails.org/latest/ref/Domain%20Classes/namedQueries.html –

回答

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

我显示了一个标准查询,因为这是你在你的问题中使用的。根据问题中不明确的某些细节,具有一些好处的另一选择可能是利用分离标准查询可组合的事实。 –

相关问题