and和or组合重点代码:
List<Predicate> tempAnd = new ArrayList<>(); //临时查询条件and
List<Predicate> tempOr = new ArrayList<>(); //临时查询条件or
if (!StringUtils.isNullOrEmpty(user.getDeptId()) && user.getDeptId() != 0) {
//查询条件1:用户部门ID与查询的部门ID一致
tempOr.add(cb.equal(deptId, user.getDeptId()));
//查询条件2:用户名与查询用户名一致
tempOr.add(cb.equal(userName,user.getUserName));
}
//复杂查询:and和or的组合使用
//1.定义一个Predicate数组
Predicate[] array_and = new Predicate[tempAnd.size()];
//2.将and查询的条件添加到数组中
Predicate Pre_And = cb.and(tempAnd.toArray(array_and));
//3.再定义一个数组
Predicate[] arrayOr = new Predicate[tempOr.size()];
//4.将or查询的条件添加到数组中
Predicate Pre_Or = cb.or(tempOr.toArray(arrayOr));
//构建组合查询条件
query.where(Pre_And, Pre_Or);
return query.getRestriction();
- 注意,and的优先级高于or,并且or条件如果只有一个查询条件,只会构成and条件
- 前提:有三个条件(a,b,c) select u.* from user u where
- 使用and条件 where后面添加的条件为: a and b and c
- 使用or条件,只有一个条件a ,where 后面条件的条件为 1