JPA又本身的Pageable來幫助咱們實現分頁,Mybatis有PageHelper幫咱們實現分頁,下面直接貼代碼。git
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
複製代碼
其實就是JPA的依賴。github
/**
* 查詢所有
*/
@Override
public ServerResponse selectAll(Integer page,Integer size) {
Pageable pageable = new PageRequest(page,size,Sort.Direction.DESC,"noticeId");
Iterator<Notice> all = noticeRepostory.findAll(pageable).iterator();
List<Notice> list = new ArrayList<Notice>();
while (all.hasNext()){
list.add(all.next());
}
if (all == null){
return ServerResponse.createByErrorMessage("查詢公告列表失敗");
}
return ServerResponse.createBySuccess(list);
}
複製代碼
更多詳細的請看spring boot2 整合(二)JPA(特別完整!)中分頁那部分。spring
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
複製代碼
/**
* 查詢消息列表
*
* @param userId
*/
@Override
public ServerResponse selectNewsList(Integer userId,Integer pageNum,Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<News> news = newsMapper.selectNewsList(userId);
PageInfo<News> appsPageInfo = new PageInfo<>(news);
if (StringUtils.isEmpty(news)){
return ServerResponse.createByErrorMessage("查詢消息列表失敗");
}
log.info("查詢到的消息數目{}",appsPageInfo.getList());
appsPageInfo.getList().forEach(p-> System.out.println(p.toString()));
return ServerResponse.createBySuccess(appsPageInfo.getList());
}
複製代碼
咱們只須要PageHelper.startPage,而後緊跟着查詢並返回一個list對象,而後用list對象建立一個PageInfo對象。bash
pageInfo有不少屬性,好比當前頁是多少,有沒有下一頁,數據一共多少等等,我這裏調用它的getList方法來獲取到news集合。app
更多詳細的請看spring boot2 整合(一)Mybatis (特別完整!) 中分頁那部分。ide