JPA实现分页查询主要利用 Page 接口,PageRequest 类。

首先通过 PageRequest.of(start, size) 获取一个 起始页为 start,一页大小为 sizePageRequest 类。

接着可以将该分页类在查询时加入到查询语句参数中即可实现查询对应分页的满足条件的数据。

@Override  
public Page<Goods> getAllByPage(Long start, Long size) {  
  
    PageRequest request = PageRequest.of(Math.toIntExact(start), Math.toIntExact(size));  
    Page<Goods> list = goodsRepository.findAll(request);  
    return list;  
}

对于获取到的 Page<T> 对象,里面包含了原始数据还有一些分页信息,如总大小,分页数量等,可以经过 pageService 处理后返回给 Controller 并提交给前端:

@Override  
public PageResponse findGoodsList(Long current, Long size) {  
  
    Page<Goods> page = goodsService.getAllByPage(current, size);  
    Long total = page.getTotalElements();  
    Long pages = (long) page.getTotalPages();  
  
    List<Goods> goods = page.getContent();  
  
    log.info("获取到的分页结果: " + goods);  
  
    return PageResponse.success(total, pages, current, size, goods);  
}

最后经由Controller返回一个Json内容即可:

@PostMapping("/api/goods/list")  
@ApiOperationLog(description = "分页查询商品")  
public PageResponse findGoodsList(Long current, Long size) {  
    return pageService.findGoodsList(current, size);  
}

拼接条件

例如要想分页查询对应userId的数据:

@PostMapping("/api/goods/userList")  
@ApiOperationLog(description = "分页查询属于用户的商品")  
public PageResponse findGoodsList(Long current, Long size, Integer userId) {  
    return pageService.findGoodsList(current, size, userId);  
}

PageService:

@Override  
public PageResponse findGoodsList(Long current, Long size, Integer userId) {  
    Page<Goods> page = goodsService.getAllByPageAndUserId(current, size, userId);  
    Long total = page.getTotalElements();  
    Long pages = (long) page.getTotalPages();  
  
    List<Goods> goods = page.getContent();  
  
    log.info("获取到的条件分页结果: " + goods);  
  
    return PageResponse.success(total, pages, current, size, goods);  
}

GoodsService

@Override  
public Page<Goods> getAllByPageAndUserId(Long start, Long size, Integer userId) {  
    PageRequest pageRequest = PageRequest.of(start.intValue(), size.intValue());  
    return goodsRepository.findByMerchantId(userId, pageRequest);  
}