目录

说到多条件查询,大家肯定会想到继承JpaSpecificationExecutor<T>,但是多条件查询如何实现呢,进入JpaSpecificationExecutor中有这样的一个方法:

Page<T> findAll(Specification<T> spec, Pageable pageable);

我们只需构建一个Specification,就能实现多条件分页查询,具体实现就不细说了,直接看代码。

Repository

public interface MovieRepository extends JpaRepository<Movie, Long>,JpaSpecificationExecutor<Movie>,
    Serializable{
}

Service

public Page<Movie> findAllMovie(Pageable pageable,String status,String rank) {
        logger.info("Select all Movie");
        pageable = PageUtil.getPageRequest(pageable.getPageNumber(), null);
        Specification querySpecification = (Specification<Movie>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            query.orderBy(cb.desc(root.get("id").as(Integer.class)));
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            if ("hot".equals(rank)) {
                query.orderBy(cb.desc(root.get("clicks").as(Integer.class)));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return movieRepository.findAll(querySpecification,pageable);
    }

PageUtil

分页我们写一个工具类来指定默认页,默认大小,排序方式。

public class PageUtil {
    public static PageRequest getPageRequest(Integer pageNumber, Integer pageSize, String field) {
        Sort sort = null;
        //默认页面为0,
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 0;
        } else {
            pageNumber = pageNumber - 1;
        }
        //默认页面大小18
        if (pageSize == null || pageSize < 1) {
            pageSize = 18;
        }
        //默认采用ID倒叙排列
        if (field == null) {
            sort = null;
        }else {
            sort = new Sort(Sort.Direction.DESC, field);
        }
        return new PageRequest(pageNumber, pageSize, sort);
    }

    public static PageRequest getPageRequest() {
        return getPageRequest(null, null, null);
    }

    public static PageRequest getPageRequest(Integer pageNumber, Integer pageSize) {
        return getPageRequest(pageNumber, pageSize, null);
    }
}

Controller

@GetMapping(value = "index")
    public Page<Movie> index(Pageable pageable,String status,String rank){
        return movieService.findAllMovie(pageable,status,rank);
    }

调用测试:/index?page=xxx&size=10

JPA Criteria示例:http://jpwh.org/examples/jpwh2/jpwh-2e-examples-20151103/examples/src/test/java/org/jpwh/test/querying/criteria/Restriction.java