2011-05-19 67 views
1

想象我有以下查詢:如何以幾乎相同的標準避免冗餘?

def result = Test.createCriteria().list(params) { 
    // image here a lot of assocs, criterias, ... 
} 

在您需要查詢的行數以上,例如許多情況下,列出許多控制器的操作。

def resultTotal = Test.createCriteria().list(params) { 
    // Imagine here a lot of assocs, criterias, ... 
    // Change to the criteria above is only the projection block 
    projections { rowCount() } 
} 

我該如何避免這種情況?

回答

0

您可以:

  1. 提取標準建立的條件工廠/建設者方法;
  2. 使用named queries;
  3. 使用已命名的查詢參數(!和Groovy代碼),以改變 「對飛」 的查詢,如:

static namedQueries = { 
    byLocation { Location location -> 
     if (location) { 
     ... // some more criteria logic 
     } 
    } 
} 
0

如果不分頁查詢的結果,你可以簡單地做下面的第一個查詢被調用後:

def resultTotal = result?.size() 
0

對於同一組的查詢在很多地方使用,我將它們創建爲閉包,並將其代表更改爲相關標準。 例如:

def query = { 
    projections{ 
     rowCount() 
    } 
    eq('type', myType) 
    } 

def criteria = Customer.createCriteria() 
     query.delegate = criteria 
     myType = CustomerType.guest 
     List records = criteria.list(params) { 
      query() 
     } 
0

我用TOTALCOUNT這樣的:

def list() { 
    def myInstanceList = MyInstance.createCriteria().list(params){ 
     eq('name', params.name) 
    } 
    [myInstanceList: myInstanceList, myInstanceListTotal: myInstanceList.totalCount] 
}