JPA多条件查询(精确查询、模糊查询、时间段查询)重写Specification的toPredicate方法

实现

   /**
     * 分页查询公司拥有的项目的列表
     * @param companyId
     * @return
     */
    public Page getListByCompanyPage(PageFilter pageFilter,String companyId,Date beginDate,Date endDate,String projectName) {
        Page l=projectRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cBuilder) {
                //开始,定义一个Predicate
                Predicate p = cBuilder.conjunction();
                /**精确查询**/
                p = cBuilder.and(p, cBuilder.equal(root.get("companyId"), companyId));
                /**模糊查询**/
                p = cBuilder.and(p, cBuilder.like(root.get("projectName"), "%"+projectName+"%"));
                /**时间段查询**/
                //大于等于开始时间
                p = cBuilder.and(p, cBuilder.greaterThanOrEqualTo(root.get("createTime"), beginDate));
                //小于等于结束时间
                p = cBuilder.and(p, cBuilder.lessThanOrEqualTo(root.get("createTime"), endDate));
                return p;
            }
        }, pageFilter.getPageRequest());
        return l;
    }

 

你可能感兴趣的:(SpringData,JPA,JAVA)