LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。
目录
概述
在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;
}
继续追踪:
从源码中我们看到当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
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。在整合过程中通常会配置如下代码:
从中我们其继承了 BeanDefinitionRegistryPostProcessor接口,熟悉Spring 的同学应该 已经大致想到了 其如何将 Mapper 偷梁换柱成 MapperFactoryBean了。话不多说,我们来看看 MapperScannerConfigurer是如何实现 BeanDefinitionRegistryPostProcessor的 postProcessBeanDefinitionRegistry()方法:
我们可以发现整个方法内部其实就是通过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,源码如下:
三. MapperFactoryBean
MapperScannerConfigure配置后会扫描指定包下面的Mapper接口,并将其替换为MapperFactoryBean对象,
从名字就可以看出来它又是一个FactoryBean,当用户注入指定类型的Mapper实例时,容器发现与该类型绑定的实际上是一个FactoryBean则会调用FactoryBean的getObject()方法获取要注入的对象。源码如下:
public T getObject() throws Exception {
//getSqlSession为每一次注入提供不同的SqlSession实例
return getSqlSession().getMapper(this.mapperInterface);
}
getSession()返回的是SqlSessionTemplate 实例:
四. SqlSessionTemplate、SqlSessionInterceptor
通过《MyBatis动态代理调用过程源码分析》我们知道了Mapper实例对数据库的操作最终都依赖于SqlSession实例。
在分析MapperFactoryBean::getObject()源码时,我们知道了Mapper实例是通过一个``SqlSessionTemplate对象创建的,也就是说在Spring项目中注入的Mapper对象实际上最终都执行的是SqlSessionTemplate`方法。
我们查看SqlSessionTemplate中数据库操作方法可以发现,所有的操作都委托给了一个名为sqlSessionProxy的实例去处理:
想要了解SqlSessionTempalte::sqlSessionProxy属性来源,我们还得从SqlSessionTemplate实例被注入到SqlSessionFactoryBean的地方说起,进入到SqlSessionFactoryBean::setSqlSessionFactory()方法:
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
//当我们配置时
//会调用这个方法,并创建SqlSessionTemplate封装SqlSessionFactory
if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
}
}
可以发现最终调用createSqlSessionTemplate方法创建SqlSessionTemplate,我们继续深入,可以发现最终的创建逻辑:
可以看到在动态代理类中,是先从Spring事务管理器获取SqlSession,或者在需要时创建一个新的SqlSession。试图从当前事务获取SqlSession。
如果没有,则创建一个新的;如果Spring TX是活动的,并且SpringManagedTransactionFactory被配置为事务管理器,那么它会将SqlSession与事务进行同步。
在mybatis 再被Spring 整合后,mapper底层绑定的sqlsession 实际上是一个SqlSessionInterceptor,实例,每一次执行sqlsession的方法时,sqlSessionIntercepater代理类中会创建一个与当前事务相关或获取一个与当前事务相关联的SQLsession,然后调用该sqlsession的方法实现数据库操作。
小结:
参考资料和推荐阅读
1.链接: 参考资料.
本文详细解析了MyBatis与Spring整合时如何确保SqlSession的线程安全,包括SqlSessionFactoryBean、MapperScannerConfigurer的工作原理及SqlSessionTemplate、SqlSessionInterceptor的作用。
302

被折叠的 条评论
为什么被折叠?



