Criteria query combine and predicates and or 谓词在 where 方法中
Criteria query combine and predicates and or predicates in where method
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
我尝试使用两个 preds 列表,一个用于 "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)
and CriteriaBuilder.or(Predicate... restrictions)
将谓词数组简单地组合成简单的谓词
对于获取 where (p1 and p2) or 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);
得到where p1 and (p2 or p3)
:
Predicate pFinal = cb.and(cb.or(p2all, p3all), p1all);
criteria.where(pFinal);
最后,如果您想通过将谓词数组与 or
语句连接来构建单个谓词,请使用:
Predicate p1all = cb.or(p1);
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
我尝试使用两个 preds 列表,一个用于 "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)
and CriteriaBuilder.or(Predicate... restrictions)
对于获取 where (p1 and p2) or 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);
得到where p1 and (p2 or p3)
:
Predicate pFinal = cb.and(cb.or(p2all, p3all), p1all);
criteria.where(pFinal);
最后,如果您想通过将谓词数组与 or
语句连接来构建单个谓词,请使用:
Predicate p1all = cb.or(p1);