您的位置:首页 > 编程语言 > Java开发

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

2017-08-22 15:40 567 查看

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

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

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

public List<User> getByPageService(){
int page = 0;//设置查询的页数 (从0开始) 默认0
int 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条数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: