我正在努力构建一个createCriteria
动态的。到目前为止,一切都很好:
obj
是我想要返回的域对象
rulesList
是一个映射列表,其中包含要搜索的字段、要使用的运算符以及要搜索的值
def c = obj.createCriteria()
l = c.list (max: irows, offset: offset) {
switch(obj){ //constrain results to those relevant to the user
case Vehicle:
eq("garage", usersGarage)
break
case Garage:
users {
idEq(user.id)
}
break
}
rulesList.each { rule ->
switch(rule['op']){
case 'eq':
eq("${rule['field']}", rule['value'])
break
case 'ne':
ne("${rule['field']}", rule['value'])
break
case 'gt':
gt("${rule['field']}", rule['value'])
break;
case 'ge':
ge("${rule['field']}", rule['value'])
break
case 'lt':
lt("${rule['field']}", rule['value'])
break
case 'le':
le("${rule['field']}", rule['value'])
break
case 'bw':
ilike("${rule['field']}", "${rule['value']}%")
break
case 'bn':
not{ilike("${rule['field']}", "${rule['value']}%")}
break
case 'ew':
ilike("${rule['field']}", "%${rule['value']}")
break
case 'en':
not{ilike("${rule['field']}", "%${rule['value']}")}
break
case 'cn':
ilike("${rule['field']}", "%${rule['value']}%")
break
case 'nc':
not{ilike("${rule['field']}", "%${rule['value']}%")}
break
}
}
}
}
上面的代码工作得很好,只是用 switch 语句看起来有点冗长。但是,如果我想添加功能以选择匹配任何规则或所有规则怎么办?我需要有条件地将规则放在or{}
. 我不能做类似的事情
if(groupOp == 'or'){
or{
}
在我通过 rulesList 然后
if(groupOp == 'or'){
}
}
之后。我能想到的就是为每个条件重复代码:
if(groupOp == 'or'){
or{
rulesList.each { rule ->
switch(rule['op']){
...
}
}
}
}
else{
rulesList.each { rule ->
switch(rule['op']){
...
}
}
现在代码看起来非常草率和重复。假设我想搜索域对象的某个属性?(例如:我想退回轮胎是某个品牌的车辆;vehicle.tires.brand,或司机与姓名匹配的车辆;vehicle.driver.name)。我是否必须做类似的事情:
switch(rule['op']){
case 'eq':
switch(thePropertiesProperty){
case Garage:
garage{
eq("${rule['field']}", rule['value'])
}
break
case Driver:
driver{
eq("${rule['field']}", rule['value'])
}
break
}
break
case 'ne':
...
}