现在的分页形式有两种:
<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);
}
}
@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);
}
public Page<Spu> getLatestPagingSpu(Integer pageNum, Integer size){
Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
return spuRepository.findAll(page);
}