通用Mapper + PageHelper:MyBatis分页插件终极实战教程
通用Mapper + PageHelper:MyBatis分页插件终极实战教程
【免费下载链接】spring-boot-demo🚀一个用来深入学习并实战 Spring Boot 的项目。项目地址: https://gitcode.com/gh_mirrors/sp/spring-boot-demo
在Spring Boot开发中,MyBatis作为一款优秀的ORM框架被广泛应用。而通用Mapper和PageHelper作为MyBatis的两款实用插件,能够极大地简化数据访问层代码,提升开发效率。本文将为你详细介绍如何在Spring Boot项目中整合通用Mapper和PageHelper,实现高效的分页查询功能。
核心依赖配置
要使用通用Mapper和PageHelper,首先需要在项目的pom.xml文件中添加相关依赖。以demo-orm-mybatis-mapper-page模块为例,关键依赖如下:
<!-- 通用Mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <!-- PageHelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.13</version> </dependency>配置Mapper扫描
在Spring Boot应用主类上添加@MapperScan注解,指定Mapper接口所在的包路径。注意这里使用的是tk.mybatis.spring.annotation.MapperScan:
@SpringBootApplication @MapperScan(basePackages = {"com.xkcoding.orm.mybatis.MapperAndPage.mapper"}) public class SpringBootDemoOrmMybatisMapperPageApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoOrmMybatisMapperPageApplication.class, args); } }定义实体类和Mapper接口
创建实体类User,对应数据库中的用户表:
public class User { private Long id; private String name; private Integer age; // 省略getter和setter方法 }创建UserMapper接口,继承Mapper接口,即可获得通用的CRUD方法:
public interface UserMapper extends Mapper<User> { // 可以添加自定义查询方法 }PageHelper分页实现
使用PageHelper进行分页查询非常简单,只需在执行查询前调用PageHelper.startPage方法:
// 分页查询示例 public PageInfo<User> getUserList(int currentPage, int pageSize) { // 设置分页参数 PageHelper.startPage(currentPage, pageSize); // 执行查询 List<User> userList = userMapper.selectAll(); // 封装分页结果 return new PageInfo<>(userList); }还可以指定排序字段:
PageHelper.startPage(currentPage, pageSize, "age DESC"); List<User> userList = userMapper.selectAll();测试分页功能
在测试类中编写测试方法,验证分页功能是否正常:
@Test public void testPageHelper() { int currentPage = 1; int pageSize = 3; PageHelper.startPage(currentPage, pageSize); List<User> userList = userMapper.selectAll(); PageInfo<User> pageInfo = new PageInfo<>(userList); System.out.println("总记录数:" + pageInfo.getTotal()); System.out.println("总页数:" + pageInfo.getPages()); System.out.println("当前页数据:" + userList.size()); }实际应用场景
在实际项目中,分页查询通常与前端表格组件配合使用。前端通过传递页码和每页条数,后端返回分页数据,包括当前页数据、总记录数、总页数等信息,以便前端渲染分页控件。
常见问题解决
分页失效问题:确保PageHelper.startPage方法在查询方法之前调用,且中间没有执行其他SQL操作。
排序字段错误:排序字段应与数据库表中的字段名保持一致,而非实体类的属性名。
通用Mapper方法不生效:检查Mapper接口是否正确继承了tk.mybatis.mapper.common.Mapper接口。
通过以上步骤,你已经掌握了在Spring Boot项目中使用通用Mapper和PageHelper实现分页查询的方法。这两个插件的结合使用,不仅简化了代码,还提高了开发效率,是MyBatis开发中的实用技巧。
如果你想深入学习更多Spring Boot相关技术,可以参考项目中的其他模块,如demo-orm-mybatis、demo-orm-mybatis-plus等,获取更多实战经验。
【免费下载链接】spring-boot-demo🚀一个用来深入学习并实战 Spring Boot 的项目。项目地址: https://gitcode.com/gh_mirrors/sp/spring-boot-demo
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
