Spring Boot + MyBatis 中使用 PageHelper 实现分页查询(超详细图文教程)

3,949 阅读3分钟

💡 一、前言

在开发企业级应用时,数据量往往非常庞大,直接将所有数据展示给用户不仅影响性能,也降低了用户体验。因此,分页查询成为了数据库操作中不可或缺的一部分。

在 Spring Boot + MyBatis 的项目中,PageHelper 是一个非常流行且功能强大的分页插件,它能够帮助我们轻松实现分页功能,而无需手动编写复杂的 SQL 分页语句。

本文将带你从零开始,一步步在 Spring Boot 项目中集成并使用 PageHelper 分页插件,并提供完整的代码示例和常见问题解决方案!


✅ 二、准备工作

1. 环境要求

2. 添加依赖

pom.xml 文件中添加 PageHelper 插件的依赖:

<!-- PageHelper 分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.7</version>
</dependency>

✅ 提示:这个 starter 包含了自动配置,无需额外配置拦截器。


🛠️ 三、使用 PageHelper 进行分页查询

1. 修改 Mapper 接口

假设我们有一个 UserMapper 接口,用于查询所有用户:

@Mapper
public interface UserMapper {
    List<User> findAll();
}

2. 在 Service 层调用 PageHelper.startPage()

在 Service 层调用 PageHelper.startPage() 方法开启分页功能:

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询数据
        List<User> users = userMapper.findAll();
        // 封装分页信息
        return new PageInfo<>(users);
    }
}

📌 注意:

  • PageHelper.startPage(pageNum, pageSize)

    必须写在查询语句之前。

  • PageInfo

    是 PageHelper 提供的一个封装了分页信息的类,包含当前页、总页数、是否有下一页等信息。


🧪 四、Controller 层返回分页数据

创建一个 Controller 类来接收前端传来的分页参数,并返回分页结果:

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public PageInfo<User> getUsers(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return userService.getUsersByPage(pageNum, pageSize);
    }
}

📈 五、测试接口

启动项目后,访问如下 URL:

http://localhost:8080/users?pageNum=1&pageSize=5

你将看到类似如下的 JSON 响应:

img

这说明你的分页功能已经成功实现!


🔍 六、常见问题与解决方案

问题描述解决方案
分页失效或不分页检查是否在查询前调用了 PageHelper.startPage()
返回的 PageInfo 数据不全确保 PageInfo 是通过查询后的 List 构造的
多表关联分页导致数据重复使用 PageHelper.orderBy() 或 SQL 中合理使用排序字段
同一个方法中多次分页无效只有第一次调用 startPage() 生效,建议拆分成多个方法

🧩 七、进阶技巧

1. 按条件排序

PageHelper.startPage(pageNum, pageSize);
PageHelper.orderBy("id DESC");
List<User> users = userMapper.findAll();

📝 八、结语

通过本文的学习,你应该已经掌握了如何在 Spring Boot + MyBatis 的项目中使用 PageHelper 分页插件,并且可以快速构建出支持分页功能的数据接口。

如果你觉得这篇文章对你有帮助,欢迎点赞、收藏、转发给更多需要的朋友!我们下期再见 👋