java - 条件查询组合和谓词和或谓词在where方法中

标签 java criteria-api

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,其中p1p2p3都是与 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/

相关文章:

java - 不使用元模型的 JPA 2 Criteria API 不区分大小写的条件

java - "Data-normalized"是什么意思?

Java学习任务+解决方案(小项目)

java - 回滚事务仍然会在 spring boot 和 hibernate 中增加主键

java - 在java中每次出现在字符串中替换一个字符

jpa - 如何按集合值查询实体

java - 使用 MapReduce 在图中查找距离为 2 的节点对

hibernate - 如何使用分组进行条件查询

java - JPA 标准 API : How to select property in nested collection

Java 标准构建器查询不为空或为空