SpringData 内置分页查询方法 (包含排序)

来源:互联网 发布:mac l4d2控制台 编辑:程序博客网 时间:2024/06/11 02:57

1、实现类repository借口,继承JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer>{}

2、service使用内部方法service.findAll<Pagealer>

public List<User> getByPageService(){int page = 0;//设置查询的页数 (从0开始) 默认0int size = 15;//设置每页显示的数据数 默认20//设置排序方式Order order1=new Order(Direction.DESC,"age");Order order2=new Order(Direction.ASC,"id");Sort sort=new Sort(order1,order2);PageRequest pageable=new PageRequest(page, size, sort);Page<User> pageUser = userRepository.findAll(pageable);List<User> users = pageUser.getContent();//获取结果集int totalPages = pageUser.getTotalPages();//获取共有多少页long totalElements = pageUser.getTotalElements();//获取共有多少条数据return users;}


好了已经使用完成了,我们来分析一下返回值Page<entity>

最后,让我们进入程序的根目录,运行命令mvn spring-boot:run将web应用启动起来,启动完成后,访问[http://localhost:8080/](http://localhost:8080/)页面,我们将看到如下结果:

{  "content":[    {"id":123,"title":"blog122","content":"this is blog content"},    {"id":122,"title":"blog121","content":"this is blog content"},    {"id":121,"title":"blog120","content":"this is blog content"},    {"id":120,"title":"blog119","content":"this is blog content"},    {"id":119,"title":"blog118","content":"this is blog content"},    {"id":118,"title":"blog117","content":"this is blog content"},    {"id":117,"title":"blog116","content":"this is blog content"},    {"id":116,"title":"blog115","content":"this is blog content"},    {"id":115,"title":"blog114","content":"this is blog content"},    {"id":114,"title":"blog113","content":"this is blog content"},    {"id":113,"title":"blog112","content":"this is blog content"},    {"id":112,"title":"blog111","content":"this is blog content"},    {"id":111,"title":"blog110","content":"this is blog content"},    {"id":110,"title":"blog109","content":"this is blog content"},    {"id":109,"title":"blog108","content":"this is blog content"}],  "last":false,  "totalPages":9,  "totalElements":123,  "size":15,  "number":0,  "first":true,  "sort":[{    "direction":"DESC",    "property":"id",    "ignoreCase":false,    "nullHandling":"NATIVE",    "ascending":false  }],  "numberOfElements":15}

通过查询结果,我们可以知道:

  • 以id倒序排列的10条数据
  • 当前页不是最后一页,后面还有数据
  • 总共有9页
  • 每页大小为15
  • 当前页为第0页
  • 当前页是第一页
  • 当前页是以id倒序排列的
  • 当前页一共有15条数据