项目中,有的地方存值以逗号分隔的方式来存储,但查询的时候是需要满足单个值或者多个值条件查询,因此用到Specification中and、or组合使用,此文用来记录,以防后用。
描述:
parentCode逗号分隔,同一parentCode下有且只能有一个名称相同的标签对象,新增传值parentCode逗号分隔,可多个,用下面查询方法来做校验。
private List<LabelInfo> getDimensionList(LabelInfo labelInfo) { Specification<LabelInfo> specification = (Root<LabelInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) -> { //parentCode条件拆分组装 String[] parentCodes = labelInfo.getParentCode().split(","); List<Predicate> predicates1 = new ArrayList<>(); for (String parentCode : parentCodes) { if (!StringUtil.isNullStr(parentCode)) { Predicate pred = criteriaBuilder.like(root.get("parentCode"), "%" + parentCode + "%"); predicates1.add(pred); } } //or条件组合 Predicate predicateOr = criteriaBuilder.or(predicates1.toArray(new Predicate[predicates1.size()])); predicateOr = criteriaBuilder.and(predicateOr); //and条件组合 List<Predicate> predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("level"), 3)); predicates.add(criteriaBuilder.like(root.get("name"), "%" + labelInfo.getName() + "%")); Predicate predicateAnd = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); //组合查询 return query.where(predicateOr, predicateAnd).getRestriction(); }; return labelInfoRepository.findAll(specification); }
标签:Predicate,JPA,Specification,predicates1,parentCode,criteriaBuilder,predicates,Da From: https://www.cnblogs.com/exmyth/p/17127430.html