logo

SpringBoot集成MyBatis-Plus:分页、条件查询与SQL日志详解

作者:carzy2025.09.18 16:02浏览量:0

简介:本文深入探讨SpringBoot项目中集成MyBatis-Plus框架时,如何高效使用分页插件、条件构造器进行动态查询,以及开启SQL打印功能优化开发调试流程。通过代码示例与配置解析,助力开发者快速掌握核心技巧。

SpringBoot集成MyBatis-Plus:分页、条件查询与SQL日志详解

在SpringBoot项目中集成MyBatis-Plus框架,可显著提升数据库操作效率。本文将围绕分页插件条件查询SQL打印开启三大核心功能展开,结合实际开发场景,提供可落地的技术方案。

一、MyBatis-Plus分页插件配置与使用

1.1 分页插件的核心作用

MyBatis-Plus的分页插件通过拦截SQL执行,自动添加LIMITOFFSET子句,实现物理分页。相比内存分页,物理分页可避免加载全量数据,提升性能。

1.2 配置步骤

  1. 添加依赖:确保mybatis-plus-boot-starter版本≥3.0。

    1. <dependency>
    2. <groupId>com.baomidou</groupId>
    3. <artifactId>mybatis-plus-boot-starter</artifactId>
    4. <version>3.5.3.1</version>
    5. </dependency>
  2. 注册分页插件:在SpringBoot配置类中添加@Bean

    1. @Configuration
    2. public class MybatisPlusConfig {
    3. @Bean
    4. public MybatisPlusInterceptor mybatisPlusInterceptor() {
    5. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    6. // 添加分页插件
    7. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    8. return interceptor;
    9. }
    10. }
  3. 分页查询示例

    1. @Service
    2. public class UserServiceImpl implements UserService {
    3. @Autowired
    4. private UserMapper userMapper;
    5. @Override
    6. public Page<User> queryByPage(Long current, Long size) {
    7. // 参数1:当前页,参数2:每页条数
    8. Page<User> page = new Page<>(current, size);
    9. return userMapper.selectPage(page, null);
    10. }
    11. }

1.3 高级配置

  • 多数据源支持:若项目使用多数据源,需在PaginationInnerInterceptor中指定DbType
  • 分页参数校验:可通过PaginationInnerInterceptor.setMaxLimit()限制最大分页条数,防止恶意请求。

二、条件构造器(Wrapper)的深度应用

2.1 条件查询的核心优势

MyBatis-Plus的条件构造器(如QueryWrapperLambdaQueryWrapper)支持链式调用,可动态拼接SQL条件,避免手写SQL的硬编码问题。

2.2 基础条件查询

  1. // 查询年龄大于25且状态为1的用户
  2. LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
  3. wrapper.gt(User::getAge, 25)
  4. .eq(User::getStatus, 1);
  5. List<User> users = userMapper.selectList(wrapper);

2.3 复杂条件组合

  1. 嵌套条件:使用and()/or()实现逻辑分组。

    1. wrapper.nested(w -> w.eq(User::getName, "张三").or().eq(User::getName, "李四"))
    2. .isNotNull(User::getEmail);
  2. 模糊查询

    1. wrapper.like(User::getName, "张"); // 类似SQL的LIKE '%张%'
    2. wrapper.likeLeft(User::getName, "张"); // LIKE '张%'
  3. 排序与分组

    1. wrapper.orderByDesc(User::getCreateTime)
    2. .groupBy(User::getDeptId);

2.4 更新与删除条件

  1. // 更新状态为0的用户
  2. LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
  3. updateWrapper.eq(User::getStatus, 1)
  4. .set(User::getStatus, 0);
  5. userMapper.update(null, updateWrapper);
  6. // 条件删除
  7. LambdaQueryWrapper<User> deleteWrapper = new LambdaQueryWrapper<>();
  8. deleteWrapper.lt(User::getLoginCount, 5);
  9. userMapper.delete(deleteWrapper);

三、SQL打印与性能优化

3.1 开启SQL日志的必要性

在开发阶段,开启SQL打印可快速定位以下问题:

  • 生成的SQL是否符合预期
  • 参数绑定是否正确
  • 是否存在N+1查询问题

3.2 配置方式

  1. application.yml配置

    1. mybatis-plus:
    2. configuration:
    3. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  2. 日志框架集成(推荐):
    若项目使用Logback或Log4j2,可在logback-spring.xml中配置:

    1. <logger name="com.baomidou.mybatisplus" level="DEBUG"/>
    2. <logger name="你的Mapper包路径" level="DEBUG"/>

3.3 日志内容解析

开启后,控制台会输出如下信息:

  1. ==> Preparing: SELECT id, name, age FROM user WHERE age > ? AND status = ?
  2. ==> Parameters: 25(Integer), 1(Integer)
  3. <== Total: 10

3.4 性能优化建议

  1. 生产环境关闭:通过spring.profiles.active区分环境配置。
    ```yaml
    spring:
    profiles:
    active: dev

spring:
profiles: dev
mybatis-plus:
configuration:

  1. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

spring:
profiles: prod
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl

  1. 2. **慢SQL监控**:结合Druid等连接池,配置慢SQL阈值。
  2. ```yaml
  3. spring:
  4. datasource:
  5. druid:
  6. filter:
  7. stat:
  8. slow-sql-millis: 2000
  9. log-slow-sql: true

四、常见问题与解决方案

4.1 分页失效问题

  • 现象:分页后数据量未减少
  • 原因:未正确注册分页插件或拦截器顺序错误
  • 解决:确保MybatisPlusInterceptor@Bean方法中优先注册

4.2 条件查询结果不符预期

  • 案例:使用eq查询却返回多条数据
  • 排查:检查数据库字段是否存在NULL值(eq对NULL无效,需改用isNull

4.3 SQL日志不显示

  • 检查点
    1. 日志级别是否设置为DEBUG
    2. Mapper接口是否被Spring管理
    3. 是否使用了@MapperScan注解

五、最佳实践总结

  1. 分页插件:始终在配置类中注册,避免重复创建
  2. 条件查询:优先使用Lambda表达式防止字段名硬编码
  3. SQL日志:开发环境开启,生产环境通过Profile动态控制
  4. 性能监控:结合Actuator暴露慢SQL指标

通过合理配置MyBatis-Plus的三大功能,可显著提升开发效率与代码质量。建议开发者结合项目实际场景,灵活运用分页、条件查询与日志功能,构建高效稳定的数据库访问层。

相关文章推荐

发表评论