Spring Boot简明教程--Jpa分页

分页参数

现在的分页形式有两种:

  • PC端分页,参数为:页码 page和每页的条数 size
  • 小程序、app端分页,参数为:从第几条记录开始请求start,请求记录条数count

依赖


      com.github.dozermapper
      dozer-core
      6.5.0

定义分页参数业务类

@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 {
    private Long total;
    private Integer count;
    private Integer page;
    private Integer totalPage;
    private List items;

    public Paging(Page pageT){
        this.initPageParameters(pageT);
        this.items = pageT.getContent();

    }
    void initPageParameters(Page pageT){
        this.total = pageT.getTotalElements();
        this.count = pageT.getSize();
        this.page = pageT.getNumber();
        this.totalPage = pageT.getTotalPages();
    }
}

分页拷贝对象构建

通常情况下直接使用分页对象即可,但是某些时候我们需要将其转化为简化的VO对象,因此可通过该对象直接进行转化

public class PagingDozer extends Paging{
    public PagingDozer(Page pageT, Class kClass){
        this.initPageParameters(pageT);
        List tList = pageT.getContent();
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        List voList = new ArrayList<>();
        tList.forEach(t->{
            K vo = mapper.map(t,kClass);
            voList.add(vo);
        });
        this.setItems(voList);
    }
}

Controller层

    @GetMapping("/latest")
    public PagingDozer getLatestSpuList(@RequestParam(defaultValue = "0") Integer start,
                                                            @RequestParam(defaultValue = "10") Integer count){
        PageCounter pageCounter = CommonUtil.convertToPageParameter(start, count);
        Page page = this.spuService.getLatestPagingSpu(pageCounter.getPage(), pageCounter.getCount());
        return new PagingDozer<>(page,SpuSimplifyVO.class);
    }

Service层

    public Page getLatestPagingSpu(Integer pageNum, Integer size){
        Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
        return spuRepository.findAll(page);
    }

你可能感兴趣的:(Spring Boot简明教程--Jpa分页)