分页Page对象使用
Posted mabiao008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分页Page对象使用相关的知识,希望对你有一定的参考价值。
之前不管是mysql还是mongo等数据库,都喜欢自己造轮子去做分页查询。现在用Page来实现分页
下面实现2个功能点:
1、查询勋章实体的Page,含分页信息、勋章列表
2、勋章Page转勋章DTO对象Page,dto为列表功能所需数据。使用语法:new PageImpl(dtoList, pageable, medalPage.getTotalElements()
public Page<MedalListDTO> listMedal(Pageable pageable, MedalListQuery medalListQuery) {
Criteria criteria = new Criteria();
if (null != medalListQuery.getStatus()) {
criteria = criteria.and("status").is(medalListQuery.getStatus());
}
if(StringUtils.isNotBlank(medalListQuery.getChannelId())){
criteria = criteria.and("channelId").is(medalListQuery.getChannelId());
}
if(StringUtils.isNotBlank(medalListQuery.getName())){
criteria = criteria.and("name").is(medalListQuery.getName());
}
// 获取勋章的pege对象
Page<Medal> medalPage = medalRepository.findBy(criteria, pageable);
List<Medal> medals = medalPage.getContent();
List<MedalListDTO> dtoList = medals.stream().map(new Function<Medal, MedalListDTO>() {
@Override
public MedalListDTO apply(Medal medal) {
MedalListDTO dto = new MedalListDTO();
xxx....
return dto;
}
}).collect(Collectors.toList());
return new PageImpl(dtoList, pageable, medalPage.getTotalElements();
}
Page接口如下:
public interface Page<T> extends Slice<T> { static <T> Page<T> empty() { return empty(Pageable.unpaged()); } static <T> Page<T> empty(Pageable pageable) { return new PageImpl(Collections.emptyList(), pageable, 0L); } int getTotalPages(); long getTotalElements(); <U> Page<U> map(Function<? super T, ? extends U> var1); }
返回值:
{ "rt": { "status": 200, "appId": "xxx", "debug": null }, "data": { "content": [ { "id": "82a21594-8bf3-44a9-a2f2-f3554a958cf0", "name": "11", "channelName": "22", "taskTeamName": "22222", "createdDate": "2020-05-28T08:58:15.843+0000", "status": "已上架", "passRate": 0.92, "joinedCount": 3, "passedCount": 3, "passedRate": 1, "questionsCount": 10 } ], "pageable": { "sort": { "sorted": false, "unsorted": true, "empty": true }, "offset": 0, "pageNumber": 0, "pageSize": 2, "paged": true, "unpaged": false }, "totalElements": 4, "totalPages": 2, "last": false, "size": 2, "number": 0, "sort": { "sorted": false, "unsorted": true, "empty": true }, "numberOfElements": 2, "first": true, "empty": false }, "success": true }
以上是关于分页Page对象使用的主要内容,如果未能解决你的问题,请参考以下文章