PageHelper分页插件,最方便使用的分页插件。分页插件支持任何复杂的单表、多表分页官方文档:https://pagehelper.github.io/ 添加依赖
这里有两种方式:
在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
service
public interface UserService { public PageInfo
serviceImpl
@Servicepublic class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; //这里写了两种方式,我是比较常用第二种 @Override public PageInfo
UserMapper
public interface UserMapper extends baseMapper
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
我们刚才调用service返回的是PageInfo类,这个类主要可以帮我们计算统计我们所需的一些属性,比如总页数,是否有下一页,是否有前一页等
//测试PageInfo@Testpublic void testPage(){ UserListParam listParam = new UserListParam(); listParam.setUsername("陈"); PageInfo
启动项目并访问http://localhost:8080/user/getList,分页成功
{ code: "200", errMsg: "操作成功", data: { total: 3, list: [ { userId: 1, username: "陈某某" }, { userId: 4, username: "陈AA" } ], pageNum: 1, pageSize: 2, size: 2, startRow: 1, endRow: 2, pages: 2, prePage: 0, nextPage: 2, isFirstPage: true, isLastPage: false, hasPreviousPage: false, hasNextPage: true, navigatePages: 8, navigatepageNums: [ 1, 2 ], navigateFirstPage: 1, navigateLastPage: 2 }}
通过日志我们可以查看除了分页查询的sql,还有一条查询总条数的sql
所以如果只是需要分页的数据,直接使用limit返回会好一点如果是前台分页列表,需要总数,总页数等,使用pageHelper适当一点
SELECT count(0) FROM t_user SELECt user_id,username FROM t_user LIMIT ?