Spring与MyBatis整合开发实战指南
2026/7/29 10:46:49 网站建设 项目流程

1. Spring与MyBatis整合概述

在企业级Java开发中,Spring框架和MyBatis持久层框架的组合堪称黄金搭档。我使用这套技术栈已有8年时间,从早期的XML配置到现在的注解驱动,见证了整个技术演进过程。这种组合既能享受Spring的IoC容器管理和事务控制,又能利用MyBatis灵活的SQL映射能力,特别适合需要精细控制SQL又不想放弃ORM便利性的场景。

2. 环境准备与基础配置

2.1 依赖管理

使用Maven构建项目时,需要引入以下核心依赖(以Spring Boot为例):

<dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis Spring Boot Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>

注意:MyBatis Starter的版本需要与Spring Boot版本匹配,不兼容的版本组合会导致奇怪的异常。

2.2 数据源配置

在application.yml中配置数据源:

spring: datasource: url: jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC username: root password: yourpassword driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 20 minimum-idle: 5

3. MyBatis核心配置详解

3.1 映射器接口与XML配置

创建Mapper接口:

@Mapper public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User findById(Long id); @Insert("INSERT INTO users(name,email) VALUES(#{name},#{email})") @Options(useGeneratedKeys = true, keyProperty = "id") int insert(User user); }

或者使用XML映射文件(推荐复杂SQL使用):

<!-- UserMapper.xml --> <mapper namespace="com.example.mapper.UserMapper"> <select id="findByEmail" resultType="com.example.model.User"> SELECT * FROM users WHERE email = #{email} </select> </mapper>

3.2 动态SQL实践

MyBatis强大的动态SQL能力:

<select id="searchUsers" resultType="User"> SELECT * FROM users <where> <if test="name != null"> AND name LIKE CONCAT('%',#{name},'%') </if> <if test="email != null"> AND email = #{email} </if> <if test="ids != null and ids.size() > 0"> AND id IN <foreach item="id" collection="ids" open="(" separator="," close=")"> #{id} </foreach> </if> </where> ORDER BY id DESC </select>

4. 高级整合技巧

4.1 分页插件集成

添加PageHelper分页插件:

@Configuration public class MyBatisConfig { @Bean public PageInterceptor pageInterceptor() { PageInterceptor pageInterceptor = new PageInterceptor(); Properties properties = new Properties(); properties.setProperty("helperDialect", "mysql"); properties.setProperty("reasonable", "true"); pageInterceptor.setProperties(properties); return pageInterceptor; } }

使用示例:

PageHelper.startPage(1, 10); // 第1页,每页10条 List<User> users = userMapper.selectAll(); PageInfo<User> pageInfo = new PageInfo<>(users);

4.2 多数据源配置

配置多个数据源:

@Configuration @MapperScan(basePackages = "com.example.primary.mapper", sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory primarySqlSessionFactory( @Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setMapperLocations( new PathMatchingResourcePatternResolver() .getResources("classpath:mapper/primary/*.xml")); return factoryBean.getObject(); } @Bean public DataSourceTransactionManager primaryTransactionManager( @Qualifier("primaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }

5. 性能优化与最佳实践

5.1 二级缓存配置

启用MyBatis二级缓存:

<!-- 在mapper.xml中 --> <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>

Spring中配置缓存管理器:

@Bean public CacheManager cacheManager() { EhCacheCacheManager cacheManager = new EhCacheCacheManager(); cacheManager.setCacheManager( EhCacheManagerUtils.buildCacheManager( new ClassPathResource("ehcache.xml"))); return cacheManager; }

5.2 批量操作优化

使用批量插入提升性能:

@Insert("<script>" + "INSERT INTO users(name, email) VALUES " + "<foreach collection='users' item='user' separator=','>" + "(#{user.name}, #{user.email})" + "</foreach>" + "</script>") void batchInsert(@Param("users") List<User> users);

或者使用ExecutorType.BATCH:

@Autowired private SqlSessionTemplate sqlSessionTemplate; public void batchInsert(List<User> users) { SqlSession session = sqlSessionTemplate.getSqlSessionFactory() .openSession(ExecutorType.BATCH, false); try { UserMapper mapper = session.getMapper(UserMapper.class); for (User user : users) { mapper.insert(user); } session.commit(); } finally { session.close(); } }

6. 常见问题排查

6.1 映射问题排查

当遇到属性映射失败时:

  1. 检查数据库字段名与Java属性名是否匹配
  2. 确认是否使用了正确的resultType/resultMap
  3. 尝试在SQL中使用AS重命名列
<select id="findUser" resultType="User"> SELECT user_id AS id, user_name AS name, user_email AS email FROM t_user WHERE user_id = #{id} </select>

6.2 事务不生效场景

确保事务生效的要点:

  1. 检查方法是否为public
  2. 确认是否在同一个类中调用
  3. 验证@Transactional注解是否正确配置
@Service public class UserService { @Transactional(rollbackFor = Exception.class) public void updateUser(User user) { // 业务逻辑 } }

7. 现代Spring Boot整合方案

7.1 自动配置原理

Spring Boot自动配置的关键类:

  1. MybatisAutoConfiguration
  2. MybatisLanguageDriverAutoConfiguration
  3. MybatisPlusAutoConfiguration (如果使用MyBatis-Plus)

可以通过debug查看自动配置过程:

logging.level.org.springframework.boot.autoconfigure=DEBUG

7.2 最新功能整合

使用Spring Boot 3.x的新特性:

@Mapper public interface UserMapper { @Select(""" SELECT * FROM users WHERE create_time >= #{createTime} """) List<User> findByCreateTime(@Param("createTime") LocalDateTime createTime); }

文本块语法让SQL更清晰可读。

8. 监控与性能分析

8.1 SQL监控配置

集成P6Spy打印真实SQL:

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/test

配置spy.properties:

module.log=com.p6spy.engine.logging.P6LogFactory appender=com.p6spy.engine.spy.appender.Slf4JLogger logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|%(sql)

8.2 MyBatis指标暴露

通过Actuator暴露MyBatis指标:

management.endpoints.web.exposure.include=health,info,metrics,mybatis

然后可以访问/actuator/metrics/mybatis.executions获取执行统计。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询