先上效果图
1、复杂查询需要继承 JpaSpecificationExecutor
public interface DrugBaseInfoRepository extends JpaRepository<DrugBaseInfoEntity,Long>, JpaSpecificationExecutor<DrugBaseInfoEntity> { }
2、关键代码,查询实体类中增加自定义注解@NotCondition 用来标识哪些是不需要拼接成查询条件的字段。 然后实现类中通过反射查询实体类进行拼接。其中需要注意的是
@Data public class DrugBaseInfoQuery { //是否模糊搜索 @NotCondition private Boolean isFuzzySearch =false; private String genericName; private String rememberCode; private String manufacture; @NotCondition private Date beginDate; @NotCondition private Date endDate; }
private Page<DrugBaseInfoEntity> getDataList(DrugBaseInfoQuery query, Pageable pageable) { Specification<DrugBaseInfoEntity> querySpecifi = new Specification<DrugBaseInfoEntity>() { public Predicate toPredicate(Root<DrugBaseInfoEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> predicates = new ArrayList<>(); if (!StringUtils.isEmpty(query.getBeginDate())) { //大于或等于传入时间 predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("orderTime").as(Date.class), query.getBeginDate())); } if (!StringUtils.isEmpty(query.getEndDate())) { //小于或等于传入时间 predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("orderTime").as(Date.class), query.getEndDate())); } if (query != null) { Class<? extends DrugBaseInfoQuery> clazz = query.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field tmpField : fields) { tmpField.setAccessible(true); try { NotCondition annotation = (NotCondition) tmpField.getDeclaredAnnotation(NotCondition.class); if (tmpField.get(query) != null && annotation == null) { String name = tmpField.getName(); if(query.getIsFuzzySearch()){ // 模糊匹配 predicates.add(criteriaBuilder.like(root.get(name).as(String.class), "%"+ tmpField.get(query) + "%")); }else{ //精准查找 predicates.add(criteriaBuilder.equal(root.get(name), tmpField.get(query))); } } } catch (Exception e) { e.printStackTrace(); } } } // and到一起的话所有条件就是且关系,or就是或关系 return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } }; return drugBaseInfoRepository.findAll(querySpecifi, pageable);