springboot开发过程中JPA分页及过程中相关问题
其中涉及关键字:Pageable、Page
问题背景:
在springboot开发过程中,经常对list数据进行分页操作,而使用JPA的操作让分页实现起来尤为方便,只需要写好对应的Pageable对象,连同该对象一同传入,JPA的查询接口中就能返回对应的分页结果。以下为模拟的代码附上详解。
代码实际演示:
Pageable pageable = PageRequest.of(paging,size,sort);
//int paging:页码(0为第一页,切记)
//int size:大小(一页中取出的多少个对象)
//Sort sort:排序(降序:Sort.Direction.DESC、升序:Sort.Direction.ASC)
Page<Demo> page = demoRepository.findAll(pageable);
//Demo demo:查询的实体类
//Page<Demo> page:查询返回的实体类
//DemoRepository demoRepository:jpa接口的实现类
List<Demo> demos = page .getContent(); //得到实体类的list集合
int paging = packages.getNumber(); //得到当前页码切记页码从0开始
int totalPages = packages.getTotalPages();//得到总的页数
存在的问题、注意点:
- 当有多个参数传入,JPA接口实现类中时,pageable一定要放在最后一个参数进行传入,否则将会报错。
正确:Page page = demoRepository.findById(id,pageable);
错误:Page page = demoRepository.findById(pageable,id); - .其他问题后续补充。。。