采用JpaSpecificationExecutor中分页用法

采用JpaSpecificationExecutor中分页用法

      • 创建Specification对象
      • 分页查询
      • LabelDao

创建Specification对象

    private Specification<Label> createSpecification(Label label){
        Specification specification = new Specification<Label>(){
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if(label.getLabelname()!=null && !"".equals(label.getLabelname())){
                    Predicate predicate = cb.like(root.get("labelname").as(String.class), "%" + label.getLabelname() + "%");
                    list.add(predicate);
                }
                if(label.getState()!=null && !"".equals(label.getState())){
                    Predicate predicate = cb.equal(root.get("state").as(String.class), label.getState());
                    list.add(predicate);
                }
                Predicate[] parr = new Predicate[list.size()];
                //把集合中的属性复制到数组中
                parr = list.toArray(parr);
                return cb.and(parr);
            }
        };
        return specification;
    }

分页查询

    public Page<Label> pageQuery(Label label, int page, int size) {
        // 封装了一个分页对象,在springdatajpa中想要实现分页,直接传一个分页对象即可
        Pageable pageable = PageRequest.of(page-1, size);
        Specification specification = this.createSpecification(label);
        return labelDao.findAll(specification, pageable);
    }

LabelDao

package com.tensquare.base.dao;

import com.tensquare.base.pojo.Label;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface LabelDao extends JpaRepository<Label, String>, JpaSpecificationExecutor<Label> {
}

你可能感兴趣的:(【微服务】,【微服务项目】,【项目】)