springboot 多条件查询+分页

首先创建实体类entity

@Entity
@Table(name = "attachment")
public class Attachment extends IdEntity {
    private String name;
    private String ext;
    private String fileName;
    private String path;
    private int status = Status.正常.getValue();
    @Column(nullable=true)
    private int type;

    ==get、set方法==
}

创建respository 继承 JpaRepository, JpaSpecificationExecutor,JpaRepository实现简单语句查询,JpaSpecificationExecutor负责语句查询(分页等)

public interface AttachmentRepository extends JpaRepository, JpaSpecificationExecutor {

}

service实现多条件查询+分页 (Page为jpa封装好的)

public class AttachmentServiceImpl{
    @Autowired
    private AttachmentRepository attachmentRepository;

    public Page findByPage(page,size,String ext, String fileName) {
         return attachmentRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List predicatesList = new ArrayList<>();
                if(""!=ext && null!=ext){
                    predicatesList.add(criteriaBuilder.equal(root.get("ext").as(String.class),ext));
                }
                if(""!=fileName && null!=fileName){
                    predicatesList.add(criteriaBuilder.equal(root.get("ext").as(String.class),ext));
                }
                predicatesList.add(criteriaBuilder.equal(root.get("status"), Status.正常.getValue()));
                Predicate[] p = new Predicate[predicatesList.size()];
                return criteriaBuilder.and(predicatesList.toArray(p));
            }
        },PageRequest.of(page,size));  //排序可以改为PageRequest.of(page, size, Sort.Direction.ASC, "sort(排序字段)")
    }

controller层调用

 @PostMapping("list")
    public Object list(ServletRequest request, String ext, String fileName) {
        return attachmentService.findByPage(0,5,"jpg","img")  //设置起始页(起始页从0开始)、显示条数、查询条件
    }

 

你可能感兴趣的:(java,springboot)