Grails 如何在几乎相同的标准中避免冗余?
假设我有以下查询:Grails 如何在几乎相同的标准中避免冗余?,grails,Grails,假设我有以下查询: 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,
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() }
}
如何避免这种情况?您可以:
将标准创建提取到条件工厂/生成器方法;
使用
使用命名查询参数和Groovy代码!要动态更改查询,请执行以下操作:
如果不分页查询结果,只需在调用第一个查询后执行以下操作:
def resultTotal = result?.size()
对于在许多地方使用的同一组查询,我将它们创建为闭包,并将其委托更改为所讨论的条件。 例如:
def query = {
projections{
rowCount()
}
eq('type', myType)
}
def criteria = Customer.createCriteria()
query.delegate = criteria
myType = CustomerType.guest
List records = criteria.list(params) {
query()
}
我使用totalCount如下所示:
def list() {
def myInstanceList = MyInstance.createCriteria().list(params){
eq('name', params.name)
}
[myInstanceList: myInstanceList, myInstanceListTotal: myInstanceList.totalCount]
}
def list() {
def myInstanceList = MyInstance.createCriteria().list(params){
eq('name', params.name)
}
[myInstanceList: myInstanceList, myInstanceListTotal: myInstanceList.totalCount]
}