一、技术选型与集成准备
1.1 框架优势分析
MyBatis-Plus作为MyBatis的增强工具,在保留原生功能基础上提供三大核心价值:
- 零SQL开发:内置通用Mapper和条件构造器,减少80%以上基础CRUD代码
- 性能优化:内置分页插件、SQL性能分析器等企业级功能
- 扩展能力:支持Lambda表达式、ActiveRecord模式等现代开发特性
1.2 环境搭建三要素
1.2.1 依赖管理
<dependencies><!-- 核心依赖 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version> <!-- 推荐使用最新稳定版 --></dependency><!-- 数据库驱动(以MySQL为例) --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 可选:Lombok简化代码 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>
1.2.2 配置文件优化
spring:datasource:url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTCusername: rootpassword: secure123driver-class-name: com.mysql.cj.jdbc.Driverhikari: # 使用Hikari连接池maximum-pool-size: 10connection-timeout: 30000mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开发环境开启SQL日志global-config:db-config:id-type: auto # 主键自增策略table-underline: true # 开启驼峰转下划线
1.2.3 实体类设计规范
@Data // Lombok注解自动生成getter/setter@TableName("sys_user") // 显式指定表名public class User {@TableId(type = IdType.AUTO) // 主键策略private Long id;@TableField(value = "user_name") // 字段映射private String username;private Integer age;@TableLogic // 逻辑删除标记private Integer deleted;}
二、核心功能实现
2.1 基础CRUD操作
2.1.1 插入数据
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Transactionalpublic boolean saveUser(UserDTO dto) {User user = new User();BeanUtils.copyProperties(dto, user);return userMapper.insert(user) > 0;}}
2.1.2 条件查询
// 使用Lambda条件构造器List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getAge, 25).between(User::getCreateTime, startDate, endDate).orderByDesc(User::getId));// 复杂查询示例Page<User> page = new Page<>(1, 10);IPage<User> result = userMapper.selectPage(page,Wrappers.<User>lambdaQuery().like(User::getUsername, "张").isNotNull(User::getEmail));
2.2 高级功能实现
2.2.1 自定义SQL
@Mapperpublic interface UserMapper extends BaseMapper<User> {// XML方式List<User> selectByAgeRange(@Param("min") Integer min, @Param("max") Integer max);// 注解方式@Select("SELECT * FROM sys_user WHERE age BETWEEN #{min} AND #{max}")List<User> selectByAgeRangeAnnotation(@Param("min") Integer min, @Param("max") Integer max);}
2.2.2 乐观锁实现
// 实体类添加版本字段@Versionprivate Integer version;// 服务层实现@Transactionalpublic boolean updateUser(UserDTO dto) {User user = userMapper.selectById(dto.getId());if (user == null) {throw new RuntimeException("用户不存在");}BeanUtils.copyProperties(dto, user);return userMapper.updateById(user) > 0;}
三、性能优化实践
3.1 批量操作优化
// 批量插入(推荐方式)public boolean batchInsert(List<User> users) {return userMapper.insertBatchSomeColumn(users) == users.size();}// 批量更新(使用Service层实现)@Transactionalpublic boolean batchUpdate(List<User> users) {return users.stream().map(this::updateUser).filter(result -> result).count() == users.size();}
3.2 缓存策略配置
@Configurationpublic class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor());// 添加缓存插件(需实现Cache接口)interceptor.addInnerInterceptor(new CacheInterceptor());return interceptor;}}
四、常见问题解决方案
4.1 分页查询失效
现象:配置分页插件后仍返回全部数据
原因:未正确添加拦截器或SQL未使用分页参数
解决方案:
- 检查MybatisPlusConfig配置
- 确保查询方法使用Page对象作为参数
- 检查SQL是否包含
LIMIT关键字(插件会自动处理)
4.2 字段映射错误
现象:实体类属性与数据库字段不匹配
解决方案:
- 使用
@TableField显式指定映射关系 - 开启全局驼峰转换配置
- 检查数据库字段命名规范(推荐使用下划线风格)
4.3 多数据源配置
@Configuration@MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")public class PrimaryDataSourceConfig {// 主数据源配置...}@Configuration@MapperScan(basePackages = "com.example.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")public class SecondaryDataSourceConfig {// 从数据源配置...}
五、最佳实践建议
- 统一异常处理:通过
@ControllerAdvice实现全局异常捕获 - DTO转换层:使用MapStruct等工具实现VO/DTO/Entity转换
- 代码生成器:利用MyBatis-Plus Generator快速生成基础代码
- SQL监控:集成Druid等监控工具实时观察SQL执行情况
- 单元测试:使用H2内存数据库编写集成测试
通过系统掌握上述技术要点,开发者可以构建出高效、稳定、易维护的数据持久层解决方案。MyBatis-Plus的强大功能结合Spring Boot的便捷性,能够显著提升开发效率,特别适合企业级应用开发场景。建议在实际项目中结合具体业务需求,灵活运用本文介绍的各种技术方案。