Spring Jpa Data多条件分页查询

目录

说到多条件查询,大家肯定会想到继承JpaSpecificationExecutor<T>

大家可能会发现中JpaSpecificationExecutor接口中有这样的一个方法:

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

哈哈,说到这里,多条件分页查询大家肯定也就明白了,就不细说了,下面贴代码。

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

标签: springboot Spring Jpa Data

声明:本博客如无特殊说明皆为原创,转载请注明来源:Spring Jpa Data多条件分页查询谢谢!

相关文章

精彩评论
  1. 蓝天 蓝天

    好像有点道理。 icon_question.png

  2. 蓝天 蓝天

    spring data jpa 的分页是真的死板 icon_evil.png

发表评论:

icon_question.pngicon_razz.pngicon_sad.pngicon_evil.pngicon_exclaim.pngicon_smile.pngicon_redface.pngicon_biggrin.pngicon_surprised.pngicon_eek.pngicon_confused.pngicon_cool.pngicon_lol.pngicon_mad.pngicon_twisted.pngicon_rolleyes.pngicon_wink.pngicon_idea.pngicon_arrow.pngicon_neutral.pngicon_cry.pngicon_mrgreen.png