欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

SpringBoot中使用PageHelper分页

时间:2023-07-07
前言

PageHelper分页插件,最方便使用的分页插件。分页插件支持任何复杂的单表、多表分页官方文档:https://pagehelper.github.io/ 添加依赖

com.github.pagehelper pagehelper-spring-boot-starter

配置文件

这里有两种方式:

在mybatis的全局配置文件中配置

在application.yml文件中配置

# pageHelper分页配置pagehelper: helper-dialect: mysql reasonable: true support-methods-arguments: true

简单使用

举个例子,前台用户列表数据展示

通用类准备

public class AjaxResponse{ private String code; private String errMsg; private Object data; public AjaxResponse(String code, String errMsg, Object data) { this.code = code; this.errMsg = errMsg; this.data = data; } public AjaxResponse(String code, String errMsg) { this.code = code; this.errMsg = errMsg; } public static AjaxResponse suc(Object data){ return new AjaxResponse("200", "操作成功", data); } public static AjaxResponse err(String errMsg){ return new AjaxResponse("400", errMsg); } //省略get set}public class PageParam implements IPage { //页码 private Integer pageNum = 1; //页数,我这里设置默认设置2,一般是10,20 private Integer pageSize = 2; //排序 private String orderBy; @Override public Integer getPageNum() { return pageNum; } @Override public Integer getPageSize() { return pageSize; } @Override public String getOrderBy() { return orderBy; }}

流程类准备

参数实体,主要用于接收前台查询条件,以及pageNum和pageSize等参数

public class UserListParam extends PageParam { //用户名 private String username; //....其他参数 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }}

controller

@Controller@RequestMapping("/user")public class UserController { @Resource UserService userService; @GetMapping(value = "/getList") @ResponseBody public AjaxResponse getList(UserListParam listParam){ //这里接收一个PageInfo,包含了返回的list,总页数,总数等前台所需数据 PageInfo pageInfo = userService.getPageList(listParam); return AjaxResponse.suc(pageInfo); }}

service

public interface UserService { public PageInfo getPageList(UserListParam listParam);}

serviceImpl

@Servicepublic class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; //这里写了两种方式,我是比较常用第二种 @Override public PageInfo getPageList(UserListParam listParam) { return PageHelper.startPage(listParam.getPageNum(), listParam.getPageSize()) .doSelectPageInfo(() -> userMapper.getPageList(listParam)); }}

UserMapper

public interface UserMapper extends baseMapper { List getPageList(UserListParam param);}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?> user_id, username