1.引入依賴
<!--分頁插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
2.在yml文件中添加配置
可以省略,這個版本有默認值。
3.示例代碼
返回結果處理工具類:
public class PageHelperVoHandler<T> { public PageResult<T> resultHandler(PageInfo<T> pageList, Integer currentPage, Integer pageSize) { try { //總記錄數 long total = pageList.getTotal(); //判斷:如果查詢出來的結果為空,則直接返回null if (total <= 0) { return new PageResult<T>(StatusCode.OK, Msg.SELECTOK, total, new ArrayList<>()); } //總頁數 long totalPages = total / pageSize; if (total % pageSize != 0) { totalPages++; } //判斷:當前頁大於總頁數,返回null if (currentPage <= totalPages) { return new PageResult<T>(StatusCode.OK, Msg.SELECTOK, total, pageList.getList()); } else { return new PageResult<T>(StatusCode.OK, "當前頁的值不能大於總頁數的值:" + totalPages, pageList.getTotal(), null); } } catch (Exception e) { throw new RuntimeException("分頁結果處理異常"); } } }
實現類:
@Service @Slf4j @Transactional(rollbackFor = Exception.class) public class ProvinceService { @Autowired private ProvinceMapper provinceMapper; public PageInfo<Province> findPageByCondition(ProvinceQueryCondition queryCondition, int currentPage, int pageSize) { try { log.info("省份管理實現類-條件+分頁查詢-入參:queryCondition:{},currentPage:{},pageSize:{}", queryCondition, currentPage, pageSize); PageHelper.startPage(currentPage, pageSize); return PageInfo.of(provinceMapper.findPageByCondition(queryCondition)); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(); } } }
controller控制層:
@CrossOrigin @RequestMapping("/nide/provinceManage") @Api(tags = "省份管理初級接口") @RestController @Slf4j public class ProvinceController { @Autowired private ProvinceService provinceService; @ApiOperation("條件分頁查詢省份信息列表") @PostMapping("/findPageByCondition/{currentPage}/{pageSize}") public PageResult<Province> findPageByCondition(@RequestBody ProvinceQueryCondition queryCondition, @PathVariable int currentPage, @PathVariable int pageSize) { log.info("省份管理初級接口-條件分頁查詢-入參:queryCondition:{},currentPage:{},pageSize{}", queryCondition, currentPage, pageSize); try { PageInfo<Province> provinceList = provinceService.findPageByCondition(queryCondition, currentPage, pageSize); return new PageHelperVoHandler<Province>().resultHandler(provinceList, currentPage, pageSize);//調用上邊的工具類 } catch (Exception e) { log.error(e.getMessage(), e); return new PageResult<>(StatusCode.ERROR, Msg.SELECTERROR, 0L, null); } } }
