一、为什么需要分页?
如果不进行分页,那么就意味着要查询和渲染数据库中所有的符合条件的数据,会出现查询缓慢,渲染大量数据造成卡顿。
分页查询是解决上述问题的经典方案。本文介绍在 Spring Boot + MyBatis 项目中,如何使用 PageHelper 快速实现分页功能。
二、PageHelper 简介
PageHelper 是 MyBatis 生态中非常流行的分页插件,它的核心优势在于:
1.操作简单,只需在查询前调用 startPage(),无需修改原有 SQL。
2.自动化,自动拦截 SQL,拼接 LIMIT 语句并执行 count 查询,其原理就是帮你写LIMIT语句。
3.易集成,提供 Spring Boot Starter,开箱即用。
三、环境搭建
在 pom.xml 中添加 PageHelper 的 Spring Boot Starter:
XML
<!-- pageHelper 坐标 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
为了前后端数据格式统一,定义一个通用的分页结果类 PageBean:
java
public class PageBean<T> {
private Long total; // 总记录数
private List<T> items; // 当前页数据列表
}
total:告诉前端一共有多少条数据,用于计算总页数
items:当前页的具体数据
四、核心使用方式
十分简单,只需一行代码就能开启分页查询:
java
//开启分页查询 PageHelp
PageHelper.startPage(pageNum,pageSize);
//直接进入mapper层即可,pagehelper会自动插入LIMIT语句
List<Article>as= articleMapper.list(userid,categoryId,state);
五、实战:文章列表分页查询
以项目中的文章列表查询为例,完整展示从 Controller 到 Mapper 的分页实现链路。
Controller 层
接收前端传来的分页参数和查询条件:
java
@GetMapping
public Result<PageBean<Article>> list(
Integer pageNum,
Integer pageSize,
@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) String state
) {
PageBean<Article> pb = articleService.list(pageNum, pageSize, categoryId, state);
return Result.success(pb);
}
要点说明:
pageNum:当前页码(从 1 开始)
pageSize:每页显示条数
categoryId 和 state 是业务查询条件,使用 required = false 表示可选
注意返回值的类型。
Service 层
这是分页逻辑的核心层:
java
@Override
public PageBean<Article> list(Integer pageNum, Integer pageSize,
Integer categoryId, String state) {
// 1. 创建 PageBean 对象
PageBean<Article> pb = new PageBean<>();
// 2. 开启分页查询
PageHelper.startPage(pageNum, pageSize);
// 3. 调用 Mapper 查询(此时返回的 List 实际是 Page 类型)
Map<String, Object> map = ThreadLocalUtil.get();
Integer userid = (Integer) map.get("id");
List<Article> as = articleMapper.list(userid, categoryId, state);
// 4. 强转为 Page 对象,获取分页信息
Page<Article> p = (Page<Article>) as;
// 5. 封装结果
pb.setTotal(p.getTotal());
pb.setItems(p.getResult());
return pb;
}
第四步转化的目的是使用Page类中的方法获取具体的分页信息,这个类是由Pagehelper提供的。
Mapper 层
正常写就行,没有什么变动:
XML
<select id="list" resultType="org.example.pojo.Article">
select * from article
<where>
<if test="categoryId != null">
category_id = #{categoryId}
</if>
<if test="state != null">
and state = #{state}
</if>
and create_user = #{userid}
</where>
</select>
PageHelper 会自动完成两件事:
执行 count 查询:SELECT COUNT(*) FROM article WHERE ...
拼接分页 SQL:在原 SQL 后添加 LIMIT offset, pageSize
六、PageHelper 工作原理(简述)
PageHelper 通过 MyBatis 的 Interceptor(拦截器) 机制,在执行查询时自动改写 SQL。startPage() 方法将分页参数放入 ThreadLocal,确保同一线程中的下一次查询被拦截处理。属于AOP编程思想,但并不是通过SpringBoot的AOP实现的,而是基于MyBatis的拦截机制。
七、总结
通过 PageHelper,我们在 Spring Boot 项目中实现了近乎零侵入的分页功能:
加依赖:pagehelper-spring-boot-starter
封装结果 : PageBean<T>
一行开启 : PageHelper.startPage(pageNum, pageSize)
正常查询 : Mapper SQL 无需改动
进行强转:List->Page
提取结果 : Page.getTotal() + Page.getResult()
这种设计让分页逻辑与业务代码完全解耦,是我们日常开发中非常推荐的分页方案。