spring-boot List轉(zhuǎn)Page的方法步驟
需求:班級與教師是多對多
關(guān)系,在后臺班級管理需要添加一個接口,傳入教師的id和pageable,返回帶分頁數(shù)據(jù)的班級信息。
Page<Klass> pageByTeacher(Long teacherId, Pageable pageable);
一開始打算是在KlassRepository(繼承自PagingAndSortingRepository)中添加一個類似findByElementId的接口,然后直接返回帶分頁的數(shù)據(jù)。但是試了幾次并不成功,無論是把teacher還是將帶teacher的List傳入方法中都失敗。
換了一種思路,直接調(diào)TeacherRepository的FindById()方法找到teacher,然后返回teacher的成員klassList就行了。
Teacher teacher = teacherRepository.findById(teacherId).get(); List<Klass> klassList = teacher.getKlassList();
但是光返回klassList還不行,需要將它包裝成Page才行,去官網(wǎng)上查到了一種使用List構(gòu)造Page
的方法
PageImpl
public PageImpl(List<T> 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.
參數(shù):
content
: 要傳的List,不為空pageable
: 分頁信息,不為空total
: 可用項的總數(shù)。如果是最后一頁,考慮到給定內(nèi)容的長度,total可以被調(diào)整。這是為了緩解不一致性。(這句沒懂什么意思),可選
一開始還以為它會自己按照傳入的參數(shù)分割List
Page<Klass> klassPage = new PageImpl<Klass>(klassList, pageable, klassList.size());
結(jié)果debug發(fā)現(xiàn)不行,得手動分割,就去網(wǎng)上參考了別人的寫法
// 當(dāng)前頁第一條數(shù)據(jù)在List中的位置 int start = (int)pageable.getOffset(); // 當(dāng)前頁最后一條數(shù)據(jù)在List中的位置 int end = (start + pageable.getPageSize()) > klassList.size() ? klassList.size() : ( start + pageable.getPageSize()); // 配置分頁數(shù)據(jù) Page<Klass> klassPage = new PageImpl<Klass>(klassList.subList(start, end), pageable, klassList.size());
debug查看結(jié)果
最后為了增加復(fù)用性,改成范型方法:
public <T> Page<T> listConvertToPage(List<T> list, Pageable pageable) { int start = (int)pageable.getOffset(); int end = (start + pageable.getPageSize()) > list.size() ? list.size() : ( start + pageable.getPageSize()); return new PageImpl<T>(list.subList(start, end), pageable, list.size()); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
分享關(guān)于JAVA 中使用Preferences讀寫注冊表時要注意的地方
這篇文章介紹了關(guān)于JAVA 中使用Preferences讀寫注冊表時要注意的地方,有需要的朋友可以參考一下2013-08-08Java最簡潔數(shù)據(jù)結(jié)構(gòu)之冒泡排序快速理解
冒泡排序是編程中數(shù)據(jù)結(jié)構(gòu)繞不過的一個基礎(chǔ)點(diǎn),有關(guān)于冒泡排序的文章也有很多,但可能會比較繚亂未能理解,本章將一子u為簡潔明了的例圖帶你通關(guān)冒泡排序2021-11-11MyBatis-Plus插件機(jī)制及通用Service新功能
這篇文章主要介紹了MyBatis-Plus插件機(jī)制以及通用Service、新功能,本文通過實例圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07springmvc字符編碼過濾器CharacterEncodingFilter的使用
這篇文章主要介紹了springmvc字符編碼過濾器CharacterEncodingFilter的使用,具有很好的參考價值,希望對大家有所幫助。2021-08-08Java鏈表數(shù)據(jù)結(jié)構(gòu)及其簡單使用方法解析
這篇文章主要介紹了Java鏈表數(shù)據(jù)結(jié)構(gòu)及其簡單使用方法解析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07