博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring-boot List转Page
阅读量:7098 次
发布时间:2019-06-28

本文共 1979 字,大约阅读时间需要 6 分钟。

需求:班级与教师是多对多关系,在后台班级管理需要添加一个接口,传入教师的id和pageable,返回带分页数据的班级信息。

Page
pageByTeacher(Long teacherId, Pageable pageable);

一开始打算是在KlassRepository(继承自PagingAndSortingRepository)中添加一个类似findByElementId的接口,然后直接返回带分页的数据。但是试了几次并不成功,无论是把teacher还是将带teacher的List传入方法中都失败。

换了一种思路,直接调TeacherRepository的FindById()方法找到teacher,然后返回teacher的成员klassList就行了。

Teacher teacher = teacherRepository.findById(teacherId).get();    List
klassList = teacher.getKlassList();

但是光返回klassList还不行,需要将它包装成Page才行,去官网上查到了一种使用List构造Page的方法

PageImplpublic PageImpl(List
content, Pageable pageable, long total)Constructor of PageImpl.Parameters:content - the content of this page, must not be null.pageable - the paging information, must not be null.total - the total amount of items available. The total might be adapted considering the length of the content given, if it is going to be the content of the last page. This is in place to mitigate inconsistencies.

参数:

content: 要传的List,不为空
pageable: 分页信息,不为空
total: 可用项的总数。如果是最后一页,考虑到给定内容的长度,total可以被调整。这是为了缓解不一致性。(这句没懂什么意思),可选

一开始还以为它会自己按照传入的参数分割List

Page
klassPage = new PageImpl
(klassList, pageable, klassList.size());

clipboard.png

结果debug发现不行,得手动分割,就去网上参考了别人的写法

// 当前页第一条数据在List中的位置    int start = (int)pageable.getOffset();    // 当前页最后一条数据在List中的位置       int end = (start + pageable.getPageSize()) > klassList.size() ? klassList.size() : ( start + pageable.getPageSize());    // 配置分页数据    Page
klassPage = new PageImpl
(klassList.subList(start, end), pageable, klassList.size());

debug查看结果

clipboard.png

最后为了增加复用性,改成范型方法:

public 
Page
listConvertToPage(List
list, Pageable pageable) { int start = (int)pageable.getOffset(); int end = (start + pageable.getPageSize()) > list.size() ? list.size() : ( start + pageable.getPageSize()); return new PageImpl
(list.subList(start, end), pageable, list.size());}

转载地址:http://vyeql.baihongyu.com/

你可能感兴趣的文章
impdp导入数据时出现BUG
查看>>
在执行一个 scripts 时,在 scripts 内的变量, $0, $1 代表什么?
查看>>
Gartner:2016年十大信息安全技术(含解读)
查看>>
BYOD那些事
查看>>
symantec:硝基***针对化工厂商
查看>>
数据中心开发者定义
查看>>
Skype for Business Server 2015-04-前端服务器-0-准备
查看>>
UML与OOAD关系
查看>>
iOS网络编程-ASIHTTPRequest框架同步请求
查看>>
马哥Linux大型免费公开课即将开始(马哥多年经验首次对外公开)
查看>>
可穿戴操作系统,期待吗?(二)
查看>>
阿里巴巴赴美上市,市值将超千亿
查看>>
python写的系统常用命令(一)
查看>>
C#互操作性入门系列(三):平台调用中的数据封送处理
查看>>
程序员在囧途之部门经理的三宫六院
查看>>
能实现项目管理与BUG跟踪系统功能的Redmine
查看>>
卢松松:巧用收藏夹做网络推广
查看>>
SQL Server 2012 AlwaysOn高可用性组部署总结及截图下载
查看>>
2016年互联网SEO的营销手段
查看>>
PowerPoint 2010去掉了宏录制器
查看>>