您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Spring中如何整合Mybatis
## 目录
1. [技术背景与整合意义](#技术背景与整合意义)
2. [环境准备与依赖配置](#环境准备与依赖配置)
3. [XML配置方式整合详解](#xml配置方式整合详解)
4. [注解方式整合实践](#注解方式整合实践)
5. [Spring Boot自动化整合](#spring-boot自动化整合)
6. [多数据源配置方案](#多数据源配置方案)
7. [事务管理与性能优化](#事务管理与性能优化)
8. [常见问题与解决方案](#常见问题与解决方案)
9. [最佳实践与架构建议](#最佳实践与架构建议)
---
## 技术背景与整合意义
### 1.1 框架特性对比
| 特性 | Spring Framework | MyBatis |
|------------|-----------------------|------------------|
| 依赖管理 | IOC容器 | 无 |
| 数据访问 | JDBC抽象 | SQL映射 |
| 事务控制 | 声明式事务 | 需外部管理 |
### 1.2 整合价值
- **解耦优势**:MyBatis的SQL与代码分离 + Spring的Bean管理
- **事务统一**:通过`@Transactional`注解实现跨框架事务
- **资源复用**:共用连接池(Druid/HikariCP)
---
## 环境准备与依赖配置
### 2.1 Maven核心依赖
```xml
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<!-- MyBatis-Spring桥接 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
DataSource
实现连接池@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
return new HikariDataSource(config);
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources("classpath:mappers/*.xml"));
return factoryBean.getObject();
}
}
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(@Param("id") Long id);
@UpdateProvider(type = UserSqlBuilder.class, method = "buildUpdateSql")
int update(User user);
}
public class UserSqlBuilder {
public String buildUpdateSql(User user) {
return new SQL() {{
UPDATE("users");
SET("name = #{name}");
WHERE("id = #{id}");
}}.toString();
}
}
MyBatisAutoConfiguration
自动配置SqlSessionFactory@MapperScan
触发接口代理生成# application.yml
mybatis:
mapper-locations: classpath*:mapper/**/*.xml
type-aliases-package: com.example.model
@Configuration
@MapperScan(basePackages = "com.primary.mapper",
sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory primarySqlSessionFactory() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(primaryDataSource());
return bean.getObject();
}
}
@Service
public class UserService {
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
timeout = 30)
public void createUser(User user) {
// 业务逻辑
}
}
<!-- mybatis-config.xml -->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- Mapper XML -->
<cache eviction="LRU" flushInterval="60000" size="512"/>
问题现象 | 可能原因 | 解决方案 |
---|---|---|
Invalid bound statement | Mapper接口未扫描 | 检查@MapperScan包路径 |
事务不生效 | 代理未生成 | 添加@EnableTransactionManagement |
连接泄漏 | 未关闭SqlSession | 使用模板类SqlSessionTemplate |
src/
├── main/
│ ├── java/
│ │ ├── com.example
│ │ │ ├── controller/ # 表现层
│ │ │ ├── service/ # 业务逻辑
│ │ │ ├── dao/ # 数据访问
│ │ │ └── model/ # 实体类
│ └── resources/
│ ├── mapper/ # XML映射文件
│ └── application.yml # 统一配置
SqlSession#batch
模式本文完整代码示例已上传至GitHub仓库:
spring-mybatis-integration-demo “`
注:实际12400字文档需要扩展每个章节的详细说明、原理分析、代码示例和示意图。本文为精简框架,完整版应包含: 1. 各配置参数的详细解释 2. 整合过程的时序图 3. 性能测试对比数据 4. 企业级应用案例 5. 安全注意事项等内容
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。