源碼分析——MyBatis與Spring整合后如何保證SqlSession線程安全
在MyBatis架構中SqlSession是提供給外層調用的頂層接口,它是MyBatis對外暴露的最重要的接口,用戶通過該接口即可完成數據庫的全部操作。在上文中我們明白了我們常用的Mybatis動態代理開發實際上底層還是依賴于SqlSession。在單獨使用MyBatis框架時,我們每一次都會獲取一個全新的SqlSession,然后通過它獲取Mapper代理對象。因為MyBatis中SqlSession的實現類(DefaultSqlSession)是一個線程不安全的類,所以Mapper代理對象和其依賴的SqlSession實例需要始終保證只有一個線程運行。
但是當MyBatis與Spring整合以后,每一個Mapper接口都只有唯一個實例(單例),這樣線程安全問題就是mybatis-spring包需要首要解決的問題。
一. SqlSessionFactoryBean
我們在進行MyBatis-Spring整合時需要配置下面代碼:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 數據庫連接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加載mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:integration-config/SqlSessionConfig.xml" />
</bean>
我們配置了數據源、MyBatis核心配置文件的路徑。因此不難想象,SqlSessionFactoryBean內部實現了配置文件解析以及SqlSessionFactory對象的創建。
由于MyBatis核心配置文件的中的配置,絕大部分都能夠配置給
SqlSessionFactoryBean對象,Mybatis與Spring整合的大部分情況下,MyBatis核心配置文件是可以取消的。
在繼承關系圖中,我們發現了 InitializingBean、FactoryBean 的身影,可能清楚這個的同學,大概已經猜到了肯定有afterPropertiesSet()來創建SqlSessionFactory對象 和getObject()來獲取SqlSessionFactory對象(Spring 在Bean加載的過程中如果發現當前Bean對象是FactoryBean會去調用getObject()獲取真正的Bean對象) 。 話不多說,先看下getObject()實現:
/**
* 實現FactoryBean接口,用于返回SqlSessionFactory實例
* {@inheritDoc}
*/
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
//創建SqlSessionFactory對象
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
getObject()相對簡單,我們都知道FactoryBean子類都是通過getObject()來獲取到實際的Bean對象,這里也就是SqlSessionFactory。從源碼中我們看到當 sqlSessionFactory為null會去調用 afterPropertiesSet(),所以 SqlSessionFactory 肯定是由 afterPropertiesSet() 來實現創建的。繼續看afterPropertiesSet()實現:
/**
* 實現至InitializingBean接口,用于初始化配置并獲取SqlSessionFactory實例
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet() throws Exception {
//dataSource不能為空
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
//構建SqlSessionFactory實例
this.sqlSessionFactory = buildSqlSessionFactory();
}
afterPropertiesSet() 內部首先 驗證了 dataSource 和 sqlSessionFactoryBuilder 不為null,最后調用 buildSqlSessionFactory()方法獲取到SqlSessionFactory對象,并賦值到類字段屬性 sqlSessionFactory 。 繼續查看buildSqlSessionFactory()源碼:
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
final Configuration targetConfiguration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configuration != null) {//對應Spring與MyBatis整合配置中的SqlSessionFactoryBean中的configuration屬性
//如果configuration不為空,則使用該對象,并配置該對象
targetConfiguration = this.configuration;
if (targetConfiguration.getVariables() == null) {
targetConfiguration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
targetConfiguration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {//如果配置了configLocation屬性
//創建XMLConfigBuilder,讀取Mybatis核心配置文件
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
targetConfiguration = xmlConfigBuilder.getConfiguration();
} else {//如果既沒配configuration也沒配configLocation屬性,則加載當前SqlSeessionFactoryBean對象中配置的信息
LOGGER.debug(
() -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
targetConfiguration = new Configuration();
Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
}
Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
if (hasLength(this.typeAliasesPackage)) {//注冊包別名
scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
.filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
.filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
}
if (!isEmpty(this.typeAliases)) {
Stream.of(this.typeAliases).forEach(typeAlias -> {
targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
});
}
if (!isEmpty(this.plugins)) {//判斷是否配置插件
//注冊這些插件
Stream.of(this.plugins).forEach(plugin -> {
targetConfiguration.addInterceptor(plugin);
LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
});
}
if (hasLength(this.typeHandlersPackage)) {
//剔除配置中的匿名類、接口、抽象類,然后注冊符合要求的typeHandlersPackage
scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
.filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
.forEach(targetConfiguration.getTypeHandlerRegistry()::register);
}
if (!isEmpty(this.typeHandlers)) {
//注冊所有的TypeHandler
Stream.of(this.typeHandlers).forEach(typeHandler -> {
targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
});
}
targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);
if (!isEmpty(this.scriptingLanguageDrivers)) {
Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
targetConfiguration.getLanguageRegistry().register(languageDriver);
LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
});
}
Optional.ofNullable(this.defaultScriptingLanguageDriver)
.ifPresent(targetConfiguration::setDefaultScriptingLanguage);
if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
try {
targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}
Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
targetConfiguration.setEnvironment(new Environment(this.environment,
this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
this.dataSource));
if (this.mapperLocations != null) {
if (this.mapperLocations.length == 0) {
LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
} else {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
//創建XMLMappperBuilder解析映射配置文件
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
}
return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}
二. MapperScannerConfigure
MapperScannerConfigurer 是 mybatis-spring 項目中為了實現方便加載Mapper接口,以及將 Mapper 偷梁換柱成 MapperFactoryBean。在整合過程中通常會配置如下代碼:
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.tjd.mapper"></property>
</bean>
MapperScannerConfigurer繼承關系如下圖:

從中我們其繼承了 BeanDefinitionRegistryPostProcessor 接口,熟悉Spring 的同學應該 已經大致想到了 其如何將 Mapper 偷梁換柱成 MapperFactoryBean 了。話不多說,我們來看看 MapperScannerConfigurer 是如何實現 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry() 方法:
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}
//創建類路徑Mapper掃描器
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
/**
* 設置掃描器屬性
*/
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
if (StringUtils.hasText(lazyInitialization)) {
scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
}
//生成過濾器,只掃描指定類
scanner.registerFilters();
//掃描指定包及其子包
scanner.scan(
StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
我們可以發現整個方法內部其實就是通過 ClassPathMapperScanner 的 scan() 方法,查看 scan() 實現,發現其內部調用了關鍵方法 doScan(),那么我們來看下 doScan() 方法實現:
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
//調用父類的掃描,獲取所有符合條件的BeanDefinitionHolder對象
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
LOGGER.warn(() -> "No MyBatis mapper was found in '" + Arrays.toString(basePackages)
+ "' package. Please check your configuration.");
} else {
//處理掃描后的BeanDefinitionHolder集合,將集合中的每一個Mapper接口轉換為MapperFactoryBean
processBeanDefinitions(beanDefinitions);
}
return beanDefinitions;
}
可以看到在doScan()方法中processBeanDefinitions()方法將集合中的每一個Mapper接口轉化為MapperFactoryBean,源碼如下:
/**
* 遍歷處理BeanDefinitionHolder將其轉換為MapperFactoryBean對象,并注入Spring容器
* @param beanDefinitions
*/
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition();
//獲取被代理Mapper接口的名稱
String beanClassName = definition.getBeanClassName();
LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
+ "' mapperInterface");
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
//Mapper接口是原始的Bean,但實際上的實例是MapperFactoryBean
definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
//設置真實的實例類型MapperFactoryBean
definition.setBeanClass(this.mapperFactoryBeanClass);
//增加addToConfig屬性
definition.getPropertyValues().add("addToConfig", this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory",
new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
explicitFactoryUsed = true;
}
//增加SqlSessionTemplate屬性
if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
LOGGER.warn(
() -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate",
new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
explicitFactoryUsed = true;
//設置SqlSessionTemplate
} else if (this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
LOGGER.warn(
() -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
explicitFactoryUsed = true;
}
//將自動注入的方式修改為AUTOWIRE_BY_TYPE
if (!explicitFactoryUsed) {
LOGGER.debug(() -> "Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
}
definition.setLazyInit(lazyInitialization);
}
}
三. MapperFactoryBean
MapperScannerConfigure配置后會掃描指定包下面的Mapper接口,并將其替換為MapperFactoryBean對象,

從名字就可以看出來它又是一個FactoryBean,當用戶注入指定類型的Mapper實例時,容器發現與該類型綁定的實際上是一個FactoryBean則會調用FactoryBean的getObject()方法獲取要注入的對象。源碼如下:
public T getObject() throws Exception {
//getSqlSession為每一次注入提供不同的SqlSession實例
return getSqlSession().getMapper(this.mapperInterface);
}
getSession()返回的是SqlSessionTemplate 實例:
public SqlSession getSqlSession() {
return this.sqlSessionTemplate;
}
SqlSessionTemplate實現了SqlSession接口,然后調用getMapper()方法獲取Mapper實例:
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
四. SqlSessionTemplate、SqlSessionInterceptor
通過《MyBatis動態代理調用過程源碼分析》我們知道了Mapper實例對數據庫的操作最終都依賴于SqlSession實例。
在分析MapperFactoryBean::getObject()源碼時,我們知道了Mapper實例是通過一個``SqlSessionTemplate對象創建的,也就是說在Spring項目中注入的Mapper對象實際上最終都執行的是SqlSessionTemplate`方法。
我們查看SqlSessionTemplate中數據庫操作方法可以發現,所有的操作都委托給了一個名為sqlSessionProxy的實例去處理:
public void select(String statement, Object parameter, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, handler);
}
想要了解SqlSessionTempalte::sqlSessionProxy屬性來源,我們還得從SqlSessionTemplate實例被注入到SqlSessionFactoryBean的地方說起,進入到SqlSessionFactoryBean::setSqlSessionFactory()方法:
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
//當我們配置<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>時
//會調用這個方法,并創建SqlSessionTemplate封裝SqlSessionFactory
if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
}
}
可以發現最終調用createSqlSessionTemplate方法創建SqlSessionTemplate,我們繼續深入,可以發現最終的創建邏輯:
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) {
notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
notNull(executorType, "Property 'executorType' is required");
this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
//在這里創建了SqlSessionProxy代理對象,也是實現線程安全的
this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),
new Class[] { SqlSession.class }, new SqlSessionInterceptor());
}
可以看到在創建SqlSessionTemplate實例時,會初始化一個SqlSessionInterceptor代理實例給SqlSessionTemplate::sqlSessionProxy屬性。根據前面看到SqlSessionTemplate類中的數據庫操作最終都委托給SqlSessionTemplate::sqlSessionProxy趨勢線,也就是說SqlSessionInterceptor是MyBatis與Mybatis整合保證線程安全性的關鍵。SqlSessionInterceptor源碼:
//SqlSessionInterceptor是SqlSessionTemplate的內部類
private class SqlSessionInterceptor implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//從Spring事務管理器獲取SqlSession,或者在需要時創建一個新的SqlSession。試圖從當前事務獲取SqlSession。如果沒有,則創建一個新的。然后, 如果Spring TX是活動的,并且SpringManagedTransactionFactory被配置為事務管理器,那么它會將SqlSession與事務進行同步。
//TODO 這里應該結合Spring的事務管理源碼才能明白Spring與MyBatis結合時事務如何管理并且如何保證SqlSession線程安全
SqlSession sqlSession = getSqlSession(SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
//如果SqlSession事務沒有交由Spring管理,則提交SqlSession事務
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
// release the connection to avoid a deadlock if the translator is no loaded. See issue #22
// 如果未加載翻譯器,則釋放連接以避免死鎖
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
sqlSession = null;
//將MyBatisPersistenceException翻譯成DataAccessException
Throwable translated = SqlSessionTemplate.this.exceptionTranslator
.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
if (sqlSession != null) {
//嘗試關閉SqlSession
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
}
可以看到在動態代理類中,是先從Spring事務管理器獲取SqlSession,或者在需要時創建一個新的SqlSession。試圖從當前事務獲取SqlSession。如果沒有,則創建一個新的;如果Spring TX是活動的,并且SpringManagedTransactionFactory被配置為事務管理器,那么它會將SqlSession與事務進行同步。
也就是說,在MyBatis在被Spring整合后,Mapper底層綁定的SqlSession實際上是一個SqlSessionInterceptor實例,每一次執行SqlSession的方法時,SqlSessionInterceptor代理類中會創建或獲取一個與當前事務相關聯的SqlSession,然后調用該sqlSession的方法實現數據庫操作。
由于不同用戶調用SqlSession方法時不在同一個事務當中,每一個用戶獲取的SqlSession會不一樣,這樣能夠保證線程安全。
五. 總結
MyBatis與Spring整合后核心類的狀態:
| 類型 | 是否單例 | 說明 |
|---|---|---|
| MapperFactoryBean | 多例 | 用戶的每一個Mapper接口都唯一與一個MapperFactoryBean綁定,從Mapper接口的角度看可以理解為單例的 |
| Mapper | 多例 | 通過SqlSessionTemplate創建,每一次注入都會創建一個新的Mapper實例,但內部綁定的SqlSessionTemplate實際上是一個 |
| SqlSessionTemplate | 單例 | 雖然Mapper內部綁定的SqlSessionTemplate是單例的,但是它并不處理具體業務,更向一個分發器,將任務交給與當前事務綁定的SqlSession去執行。這樣每一個事務實際上是由一個獨立的SqlSession完成的,并不存在線程安全問題。 |
| SqlSessionInterceptor | 單例 | 具體的分發邏輯 |
MyBatis與Spring整合的時序圖:

本文只是展現了MyBatis與Spring整合的基本實現流程,更加細節的信息需要小伙伴們自己去挖掘。博主自己對MyBatis源碼進行了詳細注釋,如有需要,請移步至:GitHub或Gitee
本文闡述了自己對MyBatis源碼的一些理解,如有錯誤或不足,歡迎大佬指點,給大佬鞠個躬!!


浙公網安備 33010602011771號