有时候我们需要用jpa实现如下sql查询:
select * from tableA A where A.EVALUATION_ITEM3 + A.EVALUATION_ITEM2 + A.EVALUATION_ITEM1 < 12;
这个条件怎么通过jpa的 javax.persistence.criteria.Predicate类实现呢?
方法:
Specification<ServiceMainVo> specification = new Specification<ServiceMainVo>() {
@Override
public Predicate toPredicate(Root<ServiceMainVo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
//小区sid条件
String apartmentSid = StringUtil.getStr(param.get("apartmentSid"));
if(!"".equals(apartmentSid)){
Predicate apartmentSidPre = cb.equal(root.get("apartmentSid"), apartmentSid);
list.add(apartmentSidPre);
}
//服务类别条件
String serviceCategory = StringUtil.getStr(param.get("serviceCategory"));
if(!"".equals(serviceCategory)){
List<String> serviceCategoryList = StringUtil.getStrList(serviceCategory, ",");
In<String> in = cb.in(root.get("serviceCategory"));
for (String sc : serviceCategoryList) {
in.value(sc);
}
list.add(in);
}
//状态为1
Predicate status1Pre = cb.equal(root.get("serviceStatus"), "1");
//状态在 2,20,21,22 中
List<String> statusList = StringUtil.getStrList("2,20,21,22", ",");
In<String> statusIn = cb.in(root.get("serviceStatus"));
for (String status : statusList) {
statusIn.value(status);
}
//状态为6
Predicate status6Pre = cb.equal(root.get("serviceStatus"), "6");
//评价总分:A.EVALUATION_ITEM3 + A.EVALUATION_ITEM2 + A.EVALUATION_ITEM1
Expression<Integer> evaluationItemSum = cb.sum(cb.sum(root.get("evaluationItem1"), root.get("evaluationItem2")), root.get("evaluationItem3"));
//评价总分小于12
Predicate evaluationItemPre = cb.lessThan(evaluationItemSum, 12);
//状态为6且评价总分小于12
Predicate or3Pre = cb.and(status6Pre, evaluationItemPre);
Predicate statusPre = cb.or(status1Pre, statusIn, or3Pre);
list.add(statusPre);
return cb.and(list.toArray(new Predicate[list.size()]));
}
};
整个条件设置实现的查询条件如下:
WHERE
servicemai0_.APARTMENT_SID =?
AND (
servicemai0_.SERVICE_CATEGORY IN (?)
)
AND (
servicemai0_.SERVICE_STATUS =?
OR servicemai0_.SERVICE_STATUS IN (?, ?, ?, ?)
OR servicemai0_.SERVICE_STATUS =?
AND servicemai0_.EVALUATION_ITEM1 + servicemai0_.EVALUATION_ITEM2 + servicemai0_.EVALUATION_ITEM3 < 12
)