别再踩坑了!SpringBoot项目里Mybatis-Plus分页失效的5个排查步骤(附3.4.0版本前后配置差异)
SpringBoot项目中Mybatis-Plus分页失效的实战排查指南最近在技术社区看到不少开发者反馈Mybatis-Plus分页功能突然失效的问题。作为一个经历过类似困扰的老手我决定分享一套系统化的排查方法。不同于简单的原因-解决方案罗列本文将带你体验真实的debug过程从版本检查到配置验证一步步定位问题根源。1. 环境检查与版本确认遇到分页失效时首先要确认的是Mybatis-Plus的版本号。版本差异是导致配置失效的常见原因特别是3.4.0版本前后的重大变更。检查项目pom.xml中的依赖声明dependency groupIdcom.baomidou/groupId artifactIdmybatis-plus-boot-starter/artifactId version3.5.3/version /dependency关键版本分界点3.4.0之前使用PaginationInterceptor3.4.0之后改用MybatisPlusInterceptorPaginationInnerInterceptor提示版本不匹配会导致拦截器无法生效这是分页失效的首要排查点2. SQL日志分析与执行验证开启SQL日志是诊断分页问题的有效手段。在application.yml中添加配置mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl观察日志时重点检查是否生成了LIMIT子句分页参数是否正确传递实际执行的SQL语句结构常见异常现象日志中缺少分页参数SQL语句被重写导致分页失效多表联查时分页作用在错误的结果集上3. 拦截器配置验证根据版本差异正确配置拦截器是关键步骤。3.4.0版本配置示例Configuration public class MybatisPlusConfig { Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor new MybatisPlusInterceptor(); PaginationInnerInterceptor paginationInterceptor new PaginationInnerInterceptor(); paginationInterceptor.setMaxLimit(500L); interceptor.addInnerInterceptor(paginationInterceptor); return interceptor; } }3.4.0之前版本配置Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor interceptor new PaginationInterceptor(); interceptor.setLimit(-1); return interceptor; }配置检查要点确保配置类被Spring扫描到拦截器是否被正确初始化版本与拦截器类型是否匹配4. 分页参数传递验证正确的参数传递方式往往被忽视。以下是典型错误示例与修正方案错误示范PageUser page new Page(1, 10); ListUser users userMapper.selectList(page, null); // 错误方法正确用法PageUser page new Page(1, 10); PageUser result userMapper.selectPage(page, null); // 返回Page对象参数传递要点使用selectPage而非selectList确保返回类型为IPage或Page避免在自定义SQL中重复添加LIMIT5. 高级场景与特殊案例某些复杂场景需要额外注意多表联查分页解决方案使用子查询先分页再关联在XML中明确指定分页参数select idselectJoinPage resultMapresultMap SELECT * FROM main_table m JOIN detail_table d ON m.id d.main_id LIMIT #{offset}, #{pageSize} /select自定义分页逻辑通过继承PaginationInnerInterceptor实现public class CustomPaginationInterceptor extends PaginationInnerInterceptor { Override public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { // 自定义分页逻辑处理 } }6. 版本迁移与兼容处理从旧版迁移到3.4.0时需要注意替换拦截器实现类检查原有配置属性兼容性测试边缘案例的分页行为变更对照表特性3.4.0前3.4.0核心类PaginationInterceptorMybatisPlusInterceptor配置方式直接实例化添加InnerInterceptor最大限制setLimit()setMaxLimit()溢出处理setOverflow()保持不变在实际项目中我建议建立一个分页测试用例集覆盖以下场景基础分页查询空结果集分页最后一页不足pageSize的情况参数边界值测试