Mybatis SqlSessionTemplate 源码解析
As you may already know, to use MyBatis with Spring you need at least an SqlSessionFactory and at least one mapper interface.
MyBatis-Spring-Boot-Starter will:
- Autodetect an existing DataSource.
- Will create and register an instance of a SqlSessionFactoryBean passing that DataSource as an input.
- Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactoryBean.
- Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
在使用Mybatis与Spring集成的时候我们用到了SqlSessionTemplate 这个类。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
通过源码我们何以看到 SqlSessionTemplate 实现了SqlSession接口,也就是说我们可以使用SqlSessionTemplate 来代理以往的DefailtSqlSession完成对数据库的操作,但是DefailtSqlSession这个类不是线程安全的,所以这个类不可以被设置成单例模式的。
如果是常规开发模式 我们每次在使用DefailtSqlSession的时候都从SqlSessionFactory当中获取一个就可以了。但是与Spring集成以后,Spring提供了一个全局唯一的SqlSessionTemplate示例 来完成DefailtSqlSession的功能,问题就是:无论是多个dao使用一个SqlSessionTemplate,还是一个dao使用一个SqlSessionTemplate,SqlSessionTemplate都是对应一个sqlSession,当多个web线程调用同一个dao时,它们使用的是同一个SqlSessionTemplate,也就是同一个SqlSession,那么它是如何确保线程安全的呢?让我们一起来分析一下。
(1)首先,通过如下代码创建代理类,表示创建SqlSessionFactory的代理类的实例,该代理类实现SqlSession接口,定义了方法拦截器,如果调用代理类实例中实现SqlSession接口定义的方法,该调用则被导向SqlSessionInterceptor的invoke方法

1 public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
2 PersistenceExceptionTranslator exceptionTranslator) {
3
4 notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
5 notNull(executorType, "Property 'executorType' is required");
6
7 this.sqlSessionFactory = sqlSessionFactory;
8 this.executorType = executorType;
9 this.exceptionTranslator = exceptionTranslator;
10 this.sqlSessionProxy = (SqlSession) newProxyInstance(
11 SqlSessionFactory.class.getClassLoader(),
12 new Class[] { SqlSession.class },
13 new SqlSessionInterceptor());
14 }

核心代码就在 SqlSessionInterceptor的invoke方法当中。

1 private class SqlSessionInterceptor implements InvocationHandler {
2 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
3 //获取SqlSession(这个SqlSession才是真正使用的,它不是线程安全的)
4 //这个方法可以根据Spring的事物上下文来获取事物范围内的sqlSession
5 //一会我们在分析这个方法
6 final SqlSession sqlSession = getSqlSession(
7 SqlSessionTemplate.this.sqlSessionFactory,
8 SqlSessionTemplate.this.executorType,
9 SqlSessionTemplate.this.exceptionTranslator);
10 try {
11 //调用真实SqlSession的方法
12 Object result = method.invoke(sqlSession, args);
13 //然后判断一下当前的sqlSession是否被Spring托管 如果未被Spring托管则自动commit
14 if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
15 // force commit even on non-dirty sessions because some databases require
16 // a commit/rollback before calling close()
17 sqlSession.commit(true);
18 }
19 //返回执行结果
20 return result;
21 } catch (Throwable t) {
22 //如果出现异常则根据情况转换后抛出
23 Throwable unwrapped = unwrapThrowable(t);
24 if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
25 Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
26 if (translated != null) {
27 unwrapped = translated;
28 }
29 }
30 throw unwrapped;
31 } finally {
32 //关闭sqlSession
33 //它会根据当前的sqlSession是否在Spring的事物上下文当中来执行具体的关闭动作
34 //如果sqlSession被Spring管理 则调用holder.released(); 使计数器-1
35 //否则才真正的关闭sqlSession
36 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
37 }
38 }
39 }

在上面的invoke方法当中使用了俩个工具方法 分别是
SqlSessionUtils.getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator)
SqlSessionUtils.closeSqlSession(SqlSession session, SqlSessionFactory sessionFactory)
那么这个俩个方法又是如何与Spring的事物进行关联的呢?

1 public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
2 //根据sqlSessionFactory从当前线程对应的资源map中获取SqlSessionHolder,当sqlSessionFactory创建了sqlSession,就会在事务管理器中添加一对映射:key为sqlSessionFactory,value为SqlSessionHolder,该类保存sqlSession及执行方式
3 SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);
4 //如果holder不为空,且和当前事务同步
5 if (holder != null && holder.isSynchronizedWithTransaction()) {
6 //hodler保存的执行类型和获取SqlSession的执行类型不一致,就会抛出异常,也就是说在同一个事务中,执行类型不能变化,原因就是同一个事务中同一个sqlSessionFactory创建的sqlSession会被重用
7 if (holder.getExecutorType() != executorType) {
8 throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");
9 }
10 //增加该holder,也就是同一事务中同一个sqlSessionFactory创建的唯一sqlSession,其引用数增加,被使用的次数增加
11 holder.requested();
12 //返回sqlSession
13 return holder.getSqlSession();
14 }
15 //如果找不到,则根据执行类型构造一个新的sqlSession
16 SqlSession session = sessionFactory.openSession(executorType);
17 //判断同步是否激活,只要SpringTX被激活,就是true
18 if (isSynchronizationActive()) {
19 //加载环境变量,判断注册的事务管理器是否是SpringManagedTransaction,也就是Spring管理事务
20 Environment environment = sessionFactory.getConfiguration().getEnvironment();
21 if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
22 //如果是,则将sqlSession加载进事务管理的本地线程缓存中
23 holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
24 //以sessionFactory为key,hodler为value,加入到TransactionSynchronizationManager管理的本地缓存ThreadLocal<Map<Object, Object>> resources中
25 bindResource(sessionFactory, holder);
26 //将holder, sessionFactory的同步加入本地线程缓存中ThreadLocal<Set<TransactionSynchronization>> synchronizations
27 registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
28 //设置当前holder和当前事务同步
29 holder.setSynchronizedWithTransaction(true);
30 //增加引用数
31 holder.requested();
32 } else {
33 if (getResource(environment.getDataSource()) == null) {
34 } else {
35 throw new TransientDataAccessResourceException(
36 "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
37 }
38 }
39 } else {
40 }
41 return session;
42 }


1 public static void closeSqlSession(SqlSession session, SqlSessionFactory sessionFactory) {
2 //其实下面就是判断session是否被Spring事务管理,如果管理就会得到holder
3 SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);
4 if ((holder != null) && (holder.getSqlSession() == session)) {
5 //这里释放的作用,不是关闭,只是减少一下引用数,因为后面可能会被复用
6 holder.released();
7 } else {
8 //如果不是被spring管理,那么就不会被Spring去关闭回收,就需要自己close
9 session.close();
10 }
11 }

其实通过上面的代码我们可以看出 Mybatis在很多地方都用到了代理模式,这个模式可以说是一种经典模式,其实不紧紧在Mybatis当中使用广泛,Spring的事物,AOP ,连接池技术 等技术都使用了代理技术。在后面的文章中我们来分析Spring的抽象事物管理机制。
http://www.cnblogs.com/daxin/p/3544188.html
Mybatis SqlSessionTemplate 源码解析的更多相关文章
- MyBatis详细源码解析(上篇)
前言 我会一步一步带你剖析MyBatis这个经典的半ORM框架的源码! 我是使用Spring Boot + MyBatis的方式进行测试,但并未进行整合,还是使用最原始的方式. 项目结构 导入依赖: ...
- MyBatis 3源码解析(一)
一.SqlSessionFactory 对象初始化 //加载全局配置文件 String resource = "mybatis-config.xml"; InputStream i ...
- Mybatis-Spring SqlSessionTemplate 源码解析
在使用Mybatis与Spring集成的时候我们用到了SqlSessionTemplate 这个类. <bean id="sqlSession" class="or ...
- Mybatis SqlNode源码解析
1.ForEachSqlNode mybatis的foreach标签可以将列表.数组中的元素拼接起来,中间可以指定分隔符separator <select id="getByUserI ...
- MyBatis 3源码解析(四)
四.MyBatis 查询实现 Employee empById = mapper.getEmpById(1); 首先会调用MapperProxy的invoke方法 @Override public O ...
- MyBatis 3源码解析(三)
三.getMapper获取接口的代理对象 1.先调用DefaultSqlSession的getMapper方法.代码如下: @Override public <T> T getMapper ...
- MyBatis 3源码解析(二)
二.获取SqlSession对象 1.首先调用DefaultSqlSessionFactory 的 openSession 方法,代码如下: @Override public SqlSession o ...
- mybatis源码解析1--前言
在开始分析mybatis源码之前,需要定一个目标,也就是我们不是为了读源码而去读,一定是带着问题去读,在读的时候去寻找到答案,然后再读码的同时整理总结,学习一些高级的编码方式和技巧. 首先我们知道my ...
- Mybatis源码解析,一步一步从浅入深(二):按步骤解析源码
在文章:Mybatis源码解析,一步一步从浅入深(一):创建准备工程,中我们为了解析mybatis源码创建了一个mybatis的简单工程(源码已上传github,链接在文章末尾),并实现了一个查询功能 ...
随机推荐
- 玩耍Hibernate系列(一)--基础知识
Hibernate框架介绍: Hibernate ORM 主要用于持久化对象(最常用的框架) Hibernate Search 用于对对象进行搜索,底层基于Apache Lucene做的 Hib ...
- android开发 解决启动页空白或黑屏问题
遇到的情况: app启动时进入启动页时出现白屏页,然后大概一秒之后就出现了背景图片. 原因:app启动时加载的是windows背景,之后再加载布局文件的,所以开始的黑屏/白屏就是windows的背景颜 ...
- 【BZOJ】【3504】【CQOI2014】危桥
网络流/最大流 比较裸的最大流= = 无向图上走来回其实就等价与走两遍>_> 如果路径有相交其实不影响答案的 比较恶心的是两个人路过同一座桥,但走的方向不同互相抵消流量了…… 其实只要在第 ...
- 了解javascript中的事件(一)
本人目录如下: 零.寒暄 一.事件概念 二.事件流 三.事件处理程序 四.总结 零.寒暄 由于刚入职,近期事情繁多,今天好不容易中期答辩完事,晚上有一些时间,来给大家分享一篇博文. 这段时间每天写js ...
- WPF编程学习——布局
本文目录 1.布局简介 2.面板(Panel) 3.视图框(Viewbox) 4.滚动视图控件(ScrollViewer) 5.公共布局属性 1.布局简介 应用程序界面设计中,合理的元素布局至关重要, ...
- Best Practices for Web Apps
Mobile Web Best Practices Exceptional Performance Let's make the web faster
- JQuery表单验证插件EasyValidator,超级简单易用!
本插件的宗旨是:用户无需写一行JS验证代码,只需在要验证的表单中加入相应的验证属性即可,让验证功能易维护,可扩展,更容易上手. DEMO中已经包含了常用的正则表达式,可以直接复用,为了考虑扩展性,所以 ...
- 初识layer 快速入门
http://layer.layui.com/hello.html 如果,你初识layer,你对她不知所措,你甚至不知如何绑定事件… 那或许你应该用秒做单位,去认识她. 开始了解 第一步:部署 下载l ...
- 7 天玩转 ASP.NET MVC — 第 7 天
目录 第 1 天 第 2 天 第 3 天 第 4 天 第 5 天 第 6 天 第 7 天 0. 前言 今天是开心的一天.因为我们终于来到了系列学习的最后一节.我相信你喜欢之前的课程,并从中学到了许多. ...
- 利用GBDT模型构造新特征具体方法
利用GBDT模型构造新特征具体方法 数据挖掘入门与实战 公众号: datadw 实际问题中,可直接用于机器学**模型的特征往往并不多.能否从"混乱"的原始log中挖掘到有用的 ...