我有一个根据某些条件以编程方式提供的列表,代码如下所示:
List<Criterion> restrictionList = new ArrayList<Criterion>();
for(int i = 1; i<someconditions.length);i++){
if( condition1){
restrictionList.add(...);
} else if(condition2){
restrictionList.add(...)
} else if(condition3){
restrictionList.add(...)
}
}
在构建标准时,我这样做了:
for (int c = 0; c < restrictionList.size()-1;c++){
crit.add(Restrictions.or(restrictionList.get(c),restrictionList.get(c+1)));
}
查询字符串中的 where 子句看起来:
((A或B)AND(B或C))
由于内置子句中存在 And,因此某些结果未显示
假设我有记录 R1、R2 和 R3
R1满足条件A和C R2满足条件A R3满足条件B和C
所以(A或B)有R1,R2和R3 (B 或 C)有 R1 和 R3
由于两个条件都由 AND 约束,因此 R2 被排除在最终结果之外
如何使 where 子句看起来像:
(A或B或C)
所以当记录至少满足一个条件时才可以显示。
最佳答案
if (!restrictionList.isEmpty()) {
crit.add(or(restrictionList));
}
private Disjunction or(List<Criterion> restrictions) {
Disjunction result = Restrictions.disjunction();
for(Criterion restriction : restrictions) {
result.add(restriction);
}
return result;
}
关于java - Hibernate 使用 or 运算符和动态限制从 List<Criterion> 构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190838/