SpringBoot2.x使用Data-JPA系列四

Jpa 分页和排序

Spring-data-Jpa,帮我们实现了分页和排序,原则和上面的查询是一样的,我们可以在接口中定义,Spring-data-jpa会有一个默认的实现。

分页

分页主要有三个接口需要实现

  • PagingAndSortingRepository

  • Pageable

  • Page其中,如果XXRepository j继承自 JpaRepository,那么就已经继承了 PagingAndSortingRepository。 Pageable 是需要传入的参数的接口,它的实现类是PageRequest,PageRequest有3个构造方法,如下


//这个构造出来的分页对象不具备排序功能
public PageRequest(int page, int size) {
    this(page, size, (Sort)null);
}
//Direction和properties用来做排序操作
public PageRequest(int page, int size, Direction direction, String... properties) {
    this(page, size, new Sort(direction, properties));
}
//自定义一个排序的操作
public PageRequest(int page, int size, Sort sort) {
    super(page, size);
    this.sort = sort;
}

 

在自定义的Repository中如下定义就可以实现分页了


Page<Student> findByAge(int age, Pageable pageable);

排序

Sort

//可以输入多个Sort.Order对象,在进行多个值排序时有用
public Sort(Sort.Order... orders)
//和上面的方法一样,无非把多个参数换成了一个List
public Sort(List<Sort.Order> orders)
//当排序方向固定时,使用这个比较方便,第一个参数是排序方向,第二个开始就是排序的字段,还有一个方法第二个参数是list,原理相同
public Sort(Sort.Direction direction, String... properties)

 



 

posted on 2020-09-25 16:44  没刮胡子  阅读(183)  评论(0)    收藏  举报

导航