2017-10-17 67 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

我顯示了一個標準查詢,因爲這是你在你的問題中使用的。根據問題中不明確的某些細節,具有一些好處的另一選擇可能是利用分離標準查詢可組合的事實。 –

相關問題