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

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条数据



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值