Criteria查询在where where方法中组合和谓词和/或谓词

时间:2017-04-10 11:56:05

标签: java criteria-api

CriteriBuilder的where方法

  

根据指定的限制谓词

的组合限制查询结果

换句话说,用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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用CriteriaBuilder.and(Predicate... restrictions)CriteriaBuilder.or(Predicate... restrictions)

简单地将谓词数组合并到简单谓词中

要获取where (p1 and p2) or 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);

获取where p1 and (p2 or p3)

Predicate pFinal = cb.and(cb.or(p2all, p3all), p1all);
criteria.where(pFinal);

最后,如果要通过将谓词数组与or语句连接来构建单个谓词,请使用:

Predicate p1all = cb.or(p1);