我想创建我的条件对象并添加一些依赖于其他属性的限制。
我尝试过类似的事情......
long from, to;
use(TimeCategory) {
from = (1.month.ago).getTime() / 1000L
to = (new Date()).getTime() / 1000L
}
def crit = Map.createCriteria()
// set date range
crit.between("appear", from, to)
// if testParam1 is present
if (params.testParam1 && !(params.testParam1.equals("all") || params.testParam1.isEmpty())) {
crit.eq("test1", testParam1)
}
// if testParam2 is present
if (params.testParam2 && !(params.testParam2.equals("all") || params.testParam2.isEmpty())) {
crit.eq("test2", testParam2)
}
但是每次我收到 java.lang.IllegalArgumentException
此异常来自 HibernateCriteriaBuilder 类,其中 validateSimpleExpression 测试失败
/**
* Creates a "between" Criterion based on the property name and specified lo and hi values
* @param propertyName The property name
* @param lo The low value
* @param hi The high value
* @return A Criterion instance
*/
public Object between(String propertyName, Object lo, Object hi) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [between] with propertyName ["+propertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.between(propertyName, lo, hi));
}
private boolean validateSimpleExpression() {
if(this.criteria == null) {
return false;
}
return true;
}
知道如何动态添加一些限制吗?
最佳答案
您必须使用闭包并将其传递给条件,让我展示一些简单的示例:
def criteria = Map.createCriteria()
Closure closure = {builder ->
if(params.testParam1){
builder.eq("test1", testParam1)
}
if(params.testParam2){
builder.eq("test2", testParam2)
}
builder.beetwen("appear", from, to)
}
并且比:
def result = criteria.list(){
closure(criteria)
}
关于hibernate - Grails CriteriaBuilder 添加限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789118/