分页参数
现在的分页形式有两种:
- PC端分页,参数为:页码 page和每页的条数 size
- 小程序、app端分页,参数为:从第几条记录开始请求start,请求记录条数count
依赖
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.5.0</version>
</dependency>
定义分页参数业务类
@Getter
@Setter
@Builder
public class PageCounter {
private Integer page;
private Integer count;
}
两种参数转换
public static PageCounter convertToPageParameter(Integer start, Integer count){
int pageNum = start / count;
PageCounter pageCounter = PageCounter.builder().page(pageNum).count(count).build();
return pageCounter;
}
分页对象构建
@Getter
@Setter
@NoArgsConstructor
public class Paging<T> {
private Long total;
private Integer count;
private Integer page;
private Integer totalPage;
private List<T> items;
public Paging(Page<T> pageT){
this.initPageParameters(pageT);
this.items = pageT.getContent();
}
void initPageParameters(Page<T> pageT){
this.total = pageT.getTotalElements();
this.count = pageT.getSize();
this.page = pageT.getNumber();
this.totalPage = pageT.getTotalPages();
}
}
分页拷贝对象构建
通常情况下直接使用分页对象即可,但是某些时候我们需要将其转化为简化的VO对象,因此可通过该对象直接进行转化
public class PagingDozer<T,K> extends Paging{
public PagingDozer(Page<T> pageT, Class<K> kClass){
this.initPageParameters(pageT);
List<T> tList = pageT.getContent();
Mapper mapper = DozerBeanMapperBuilder.buildDefault();
List<K> voList = new ArrayList<>();
tList.forEach(t->{
K vo = mapper.map(t,kClass);
voList.add(vo);
});
this.setItems(voList);
}
}
Controller层
@GetMapping("/latest")
public PagingDozer<Spu, SpuSimplifyVO> getLatestSpuList(@RequestParam(defaultValue = "0") Integer start,
@RequestParam(defaultValue = "10") Integer count){
PageCounter pageCounter = CommonUtil.convertToPageParameter(start, count);
Page<Spu> page = this.spuService.getLatestPagingSpu(pageCounter.getPage(), pageCounter.getCount());
return new PagingDozer<>(page,SpuSimplifyVO.class);
}
Service层
public Page<Spu> getLatestPagingSpu(Integer pageNum, Integer size){
Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
return spuRepository.findAll(page);
}