CriteriBuilder 的 where
方法
restricts the query result according to the conjunction of the specified restriction predicates
换句话说,用 AND 连接所有谓词。我以这种方式将谓词列表传递给此方法:
criteria.where(preds.toArray(new Predicate[0]));
结果查询是这样的:
... where p1 and p2 and p3
但是我需要的是:
... where p1 and p2 or p3
我尝试使用两个 pred 列表,一个用于“ANDS”,另一个用于“ORS”:
if(preds.isEmpty() && !orPreds.isEmpty()) {
criteria.where(cb.or(orPreds.toArray(new Predicate[orPreds.size()])));
}
else if(!preds.isEmpty() && !orPreds.isEmpty()) {
criteria.where(cb.and(preds.toArray(new Predicate[preds.size()])),
cb.or(orPreds.toArray(new Predicate[orPreds.size()])));
}
else {
criteria.where(preds.toArray(new Predicate[0]));
}
但查询结果是一样的:
... where p1 and p2 and p3
有什么想法吗?
最佳答案
使用 CriteriaBuilder.and(Predicate... restrictions)
将谓词数组简单地组合成简单谓词。和 CriteriaBuilder.or(Predicate... restrictions)
用于获取where(p1和p2)或p3
,其中p1
、p2
和p3
都是与 and
语句连接的谓词数组:
Predicate[] p1 = new Predicate[2];
Predicate[] p2 = new Predicate[2];
Predicate[] p3 = new Predicate[2];
// add your predicates to the arrays.
Predicate p1all = cb.and(p1);
Predicate p2all = cb.and(p2);
Predicate p3all = cb.and(p3);
Predicate pFinal = cb.or(cb.and(p1all, p2all), p3all);
criteria.where(pFinal);
获取p1和(p2或p3)的位置
:
Predicate pFinal = cb.and(cb.or(p2all, p3all), p1all);
criteria.where(pFinal);
最后,如果您想通过将谓词数组与 or
语句连接来构建单个谓词,请使用:
Predicate p1all = cb.or(p1);
关于java - 条件查询组合和谓词和或谓词在where方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322504/