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查询

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM