SpringData JPA实现单表多条件分页查询,sql语句中同时包含 and or

1. 继承JpaSpecificationExecutor

public interface DeviceRepository extends JpaRepository<Device,String>,JpaSpecificationExecutor {

}

2.重写toPredicate 方法

 public Page findDeviceByParams(int pageNo, int pageSize, String rIndexCode, String name, String parentDevice) {

        try{
            Specification specification = new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicateList = new ArrayList<>();
                    if(!StringUtils.isEmpty(name)){
                        predicateList.add(criteriaBuilder.like(root.get("name"),"%" + name + "%"));
                    }
                    if(!StringUtils.isEmpty(parentDevice)){
                        predicateList.add(criteriaBuilder.like(root.get("parentDevice"),"%" + parentDevice + "%"));

                    }
                    predicateList.add(criteriaBuilder.equal(root.get("rIndexCode"),rIndexCode));
                    return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
                }
            };

            Sort sort = new Sort(Sort.Direction.ASC,"indexCode");
            PageRequest pageRequest = new PageRequest(pageNo-1,pageSize,sort);
            return deviceRepository.findAll(specification,pageRequest);
        }catch(Exception e){
            logger.error("查询数据库出错:" + e);
            return null;
        }


    }

   springdata jpa 实现and or 组合查询

  https://blog.csdn.net/langyan122/article/details/80608383

  https://blog.csdn.net/weixin_42475367/article/details

 springdata jpa Example查询

原文地址:https://www.cnblogs.com/heamin/p/11611400.html