使用org.springframework.data.domain.Pageable
接口類型作為入?yún)⒓纯蓪崿F(xiàn)查詢列表的分頁和排序柴钻,見下面例子:
@RequestMapping(value = "blogs", method=RequestMethod.GET)
public Page<Blog> getEntryByPageable(@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC)
Pageable pageable) {
return blogRepository.findAll(pageable);
}
當(dāng)Spring發(fā)現(xiàn)這個參數(shù)時沃于,會自動的根據(jù)request的參數(shù)來組裝該pageable對象,Spring支持的request參數(shù)如下:
- page,第幾頁璃氢,從0開始,默認(rèn)為第0頁
- size狮辽,每一頁的大小一也,這里設(shè)置為15
- sort,排序相關(guān)的信息隘竭,以property,property(,ASC|DESC)的方式組織塘秦,例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基礎(chǔ)上按lastname倒序排列
結(jié)果如下:
{
"content":[
{"id":123,"title":"blog122","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
}
上述json字段說明如下:
- content: 以id倒序排列的15條數(shù)據(jù)
- last: 當(dāng)前頁不是最后一頁讼渊,后面還有數(shù)據(jù)
- totalPages: 總共有9頁
- size: 每頁大小為15
- number: 當(dāng)前頁為第0頁
- first: 當(dāng)前頁是第一頁
- sort: 當(dāng)前頁是以id倒序排列的
- numberOfElements: 當(dāng)前頁一共有15條數(shù)據(jù)