Spring Boot 以「約定優於配置」簡化 Spring 應用開發。本文詳解 Spring Boot 整合 MyBatis 的兩種主流方式,並提供生產級配置範例。
MyBatis 需資料來源,推薦使用阿里巴巴 Druid 高效能連線池。
spring:
datasource:
name: test
url: jdbc:mysql://192.168.16.137:3306/test
username: root
password:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
關鍵點:type: com.alibaba.druid.pool.DruidDataSource 指定連線池實現。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
Starter 內部版本:
<mybatis.version> 覆蓋<mybatis-spring.version> 覆蓋mybatis:
mapperLocations: classpath:mapper/*.xml
typeAliasesPackage: tk.mapper.model
# 進階配置(可選)
config: classpath:mybatis-config.xml
typeHandlersPackage: tk.mybatis.typehandler
checkConfigLocation: true
executorType: SIMPLE # SIMPLE, REUSE, BATCH
| 優點 | 缺點 |
|---|---|
| 配置極簡,開箱即用 | 進階客製化受限(如複雜攔截器、多 SqlSessionFactory) |
| 版本管理統一 | 除錯時較難追蹤內部 Bean 建立過程 |
| 適合標準單資料源專案 | 多資料源、動態切換場景支援較弱 |
適用於需要客製化攔截器、多資料源、動態 SQL 構建等進階場景。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
@Autowired
DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
// 分頁攔截器配置
PageHelper pageHelper = new PageHelper();
Properties props = new Properties();
props.setProperty("reasonable", "true");
props.setProperty("supportMethodsArguments", "true");
props.setProperty("returnPageInfo", "check");
props.setProperty("params", "count=countSql");
pageHelper.setProperties(props);
bean.setPlugins(new Interceptor[]{pageHelper});
// Mapper XML 掃描
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
@Configuration
@AutoConfigureAfter(MyBatisConfig.class) // 必須!確保 sqlSessionFactory 已建立
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
configurer.setBasePackage("tk.mybatis.springboot.mapper");
return configurer;
}
}
坑點提醒:MapperScannerConfigurer 初始化極早,無 @AutoConfigureAfter 會因找不到 sqlSessionFactory 而拋異常。
PageHelper 至 SqlSessionFactoryBean.pluginsMapperScannerConfigurer 類別改為 tk.mybatis.spring.mapper.MapperScannerConfigurer,屬性用 Properties 配置完整整合範例(含分頁、通用 Mapper):GitHub 專案
| 場景 | 推薦方式 |
|---|---|
| 標準單資料源、快速開發、團隊 MyBatis 經驗一般 | 方式一:starter |
| 需客製化攔截器、多資料源、動態 SQL、效能調優 | 方式二:手動配置 |
| 遷移傳統 Spring+MyBatis 專案 | 方式二:配置相容性更好 |
無論選擇哪種方式,理解 SqlSessionFactory、SqlSessionTemplate、MapperScannerConfigurer 三大核心 Bean 的建立時機與關係,是排查整合問題的關鍵。