使用srpingJPA进行分页,排序和模糊查询

使用srpingJPA进行分页,排序和模糊查询,原生SQL

分页和排序

SpringJPA是使用PageRequest来进行分页查询的,PageRequest有三个构造方法,

并且排序的页码是从零开始的。

//单纯根据页码和页码大小
public PageRequest(int page, int size) {
    this(page, size, (Sort)null);
}

//直接根据Direction 和字段名进行排序
public PageRequest(int page, int size, Direction direction, String... properties) {
    this(page, size, new Sort(direction, properties));
}

//根据sort对象进行排序
public PageRequest(int page, int size, Sort sort) {
    super(page, size);
    this.sort = sort;
}

例子


//单纯根据页码和页码大小
Pageable pageable = new PageRequest(page,pageSize);

//直接根据Direction 和字段名进行排序
Pageable pageable=new PageRequest(page, pageSize,Sort.Direction.DESC,"createDate");

//根据sort对象进行排序
Sort sort = new Sort(Sort.Direction.DESC,"createDate");
Pageable pageable = new PageRequest(page,pageSize,sort);

TestReposity.findAll(pageable);

模糊查询

模糊查询需要Repository接口继承JpaSpecificationExecutor<T>接口。

public interface TestRepository extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student>{

使用 JpaSpecificationExecutor<T>Page<T> findAll(Specification<T> var1, Pageable var2);构造方法

Page<Student> pageWebSite=StudentRepository.findAll(new Specification<Student>() {

            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate=cb.conjunction();
                if(student!=null){
                    if(StringUtil.isNotEmpty(student.getName())){
                        predicate.getExpressions().add(cb.like(root.get("name"), "%"+student.getName().trim()+"%"));
                    }
                    if(student.getAge()!=null && student.getAge()>1){
                        predicate.getExpressions().add(cb.equal(root.get("age"), student.getAge()));
                    }
                }
                return predicate;
            }
        }, pageable);
        return pageWebSite.getContent();
    }

原生SQL

在Repository接口中写

    @Query(value="SELECT * FROM student WHERE score<?1 ORDER BY id DESC LIMIT 1",nativeQuery=true)
    public Student getScoreLowerStudent(Integer score);

猜你喜欢

转载自blog.csdn.net/Chirskuro/article/details/79512217