上篇 详细分析了org.mybatis.spring.mapper.MapperScannerConfigurer 和 org.mybatis.spring.SqlSessionFactoryBean的作用,可以直接看最后的总结

MapperFactoryBean是mapper接口的入口,它包含了sqlSessionFactory的封装SqlSessionTemplate,而sqlSessionFactory又包含了mapper xml的组装Configuration对象

从SqlSessionTemplate的

public <T> T getMapper(Class<T> type) {
return this.getConfiguration().getMapper(type, this);
}

开始,进入Configuration的getMapper(type,sqlsession)

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return this.mapperRegistry.getMapper(type, sqlSession);
}

进入MapperRegistry

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if(mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}

由MapperProxyFactory生成代理MapperProxy

protected T newInstance(MapperProxy<T> mapperProxy) {
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
} public T newInstance(SqlSession sqlSession) {
MapperProxy mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
return this.newInstance(mapperProxy);
}

所以最终的调用会进入MapperProxy,接下来几步在 mybatis缓存 中有介绍,会调用sqlSession(实际是SqlSessionTemplate)中的方法,看构造方法:

public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
Assert.notNull(sqlSessionFactory, "Property \'sqlSessionFactory\' is required");
Assert.notNull(executorType, "Property \'executorType\' is required");
this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = (SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[]{SqlSession.class}, new SqlSessionTemplate.SqlSessionInterceptor());
}

会对SqlSessionFactory生成代理,实际调用这个代理的方法

public <T> T selectOne(String statement) {
return this.sqlSessionProxy.selectOne(statement);
}

1. 进入SqlSessionTemplate.SqlSessionInterceptor

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);
   ......
Object t = method.invoke(sqlSession, args);
......
}

看SqlSessionUtils.getSqlSession方法:

public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
Assert.notNull(sessionFactory, "No SqlSessionFactory specified");
Assert.notNull(executorType, "No ExecutorType specified");
SqlSessionHolder holder = (SqlSessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);
if(holder != null && holder.isSynchronizedWithTransaction()) {
if(holder.getExecutorType() != executorType) {
throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");
} else {
holder.requested();
if(logger.isDebugEnabled()) {
logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
} return holder.getSqlSession();
}
} else {//进入这里呀呀呀
if(logger.isDebugEnabled()) {
logger.debug("Creating a new SqlSession");
}

       //step 1.1
SqlSession session = sessionFactory.openSession(executorType);
if(TransactionSynchronizationManager.isSynchronizationActive()) {
Environment environment = sessionFactory.getConfiguration().getEnvironment();
if(environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
if(logger.isDebugEnabled()) {
logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
}
            //step 1.2
holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
TransactionSynchronizationManager.bindResource(sessionFactory, holder);
TransactionSynchronizationManager.registerSynchronization(new SqlSessionUtils.SqlSessionSynchronization(holder, sessionFactory));
holder.setSynchronizedWithTransaction(true);
holder.requested();
} else {
if(TransactionSynchronizationManager.getResource(environment.getDataSource()) != null) {
throw new TransientDataAccessResourceException("SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
} if(logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because DataSource is not transactional");
}
}
} else if(logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active");
} return session;
}
}

1.1 进入DefaultSqlSessionFactory openSession方法:

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null; DefaultSqlSession var8;
try {
Environment e = this.configuration.getEnvironment();
//springManagedTransactionFactory
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(e);
tx = transactionFactory.newTransaction(e.getDataSource(), level, autoCommit);
Executor executor = this.configuration.newExecutor(tx, execType, autoCommit);
var8 = new DefaultSqlSession(this.configuration, executor);
} catch (Exception var12) {
this.closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);
} finally {
ErrorContext.instance().reset();
} return var8;
}

进入SpringManagedTransactionFactory的

newTransaction(e.getDataSource(), level, autoCommit);

返回

return new SpringManagedTransaction(dataSource);

这个SpringManagedTransaction比较特别,因为

private void openConnection() throws SQLException {
this.connection = DataSourceUtils.getConnection(this.dataSource);
this.autoCommit = this.connection.getAutoCommit();
this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource);
if(this.logger.isDebugEnabled()) {
this.logger.debug("JDBC Connection [" + this.connection + "] will" + (this.isConnectionTransactional?" ":" not ") + "be managed by Spring");
}
}

因为它的连接来自DataSourceUtils

public static Connection doGetConnection(DataSource dataSource) throws SQLException {
Assert.notNull(dataSource, "No DataSource specified");
ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(dataSource);
if(conHolder == null || !conHolder.hasConnection() && !conHolder.isSynchronizedWithTransaction()) {
logger.debug("Fetching JDBC Connection from DataSource");
Connection con = dataSource.getConnection();
if(TransactionSynchronizationManager.isSynchronizationActive()) {
logger.debug("Registering transaction synchronization for JDBC Connection");
ConnectionHolder holderToUse = conHolder;
if(conHolder == null) {
holderToUse = new ConnectionHolder(con);
} else {
conHolder.setConnection(con);
} holderToUse.requested();
TransactionSynchronizationManager.registerSynchronization(new DataSourceUtils.ConnectionSynchronization(holderToUse, dataSource));
holderToUse.setSynchronizedWithTransaction(true);
if(holderToUse != conHolder) {
TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
}
} return con;
} else {
conHolder.requested();
if(!conHolder.hasConnection()) {
logger.debug("Fetching resumed JDBC Connection from DataSource");
conHolder.setConnection(dataSource.getConnection());
} return conHolder.getConnection();
}
}

这一步就和 spring--事务原理 中分析的对接了!!!connection连接对象来自当前线程绑定的ConnectionHolder中的connection对象

最终 DefaultSqlSession-》Executor-》Transaction-》当前线程绑定的ConnectionHolder中的connection对象

1.2 构建SqlSessionHolder-》DefaultSqlSession,并绑定到当前线程<sessionFactory,session holder>

2. DefaultSqlSession的执行见  mybatis缓存

mybatis--MapperProxy事务的更多相关文章

  1. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

  2. Mybaits 源码解析 (十二)----- Mybatis的事务如何被Spring管理?Mybatis和Spring事务中用的Connection是同一个吗?

    不知道一些同学有没有这种疑问,为什么Mybtis中要配置dataSource,Spring的事务中也要配置dataSource?那么Mybatis和Spring事务中用的Connection是同一个吗 ...

  3. Spring Boot -- Spring Boot之@Async异步调用、Mybatis、事务管理等

    这一节将在上一节的基础上,继续深入学习Spring Boot相关知识,其中主要包括@Async异步调用,@Value自定义参数.Mybatis.事务管理等. 本节所使用的代码是在上一节项目代码中,继续 ...

  4. SpringMVC+MyBatis整合——事务管理

    项目一直没有做事务管理,这几天一直在想着解决这事,今天早上终于解决了.接下来直接上配置步骤. 我们项目采用的基本搭建环境:SpringMVC.MyBatis.Oracle11g.WebLogic10. ...

  5. myBatis之事务管理

    1. myBatis单独使用时,使用SqlSession来处理事务: public class MyBatisTxTest { private static SqlSessionFactory sql ...

  6. MyBatis+Spring 事务管理

                 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://kinglixing.blog.51cto.com/34 ...

  7. spring学习总结(mybatis,事务,测试JUnit4,日志log4j&slf4j,定时任务quartz&spring-task,jetty,Restful-jersey等)

    在实战中学习,模仿博客园的部分功能.包括用户的注册,登陆:发表新随笔,阅读随笔:发表评论,以及定时任务等.Entity层设计3张表,分别为user表(用户),essay表(随笔)以及comment表( ...

  8. Spring 与 mybatis整合---事务管理

    MyBatis与Spring整合前后事务管理有所区别 整合前:通过 session = sessionFactory.openSession(true); //或者是false 设置事务是否自动提交: ...

  9. mybatis+spring事务

    http://www.mybatis.org/spring/zh/transactions.html 第四章 事务 一个使用 MyBatis-Spring 的主要原因是它允许 MyBatis 参与到 ...

  10. Spring+JTA+Atomikos+mybatis分布式事务管理

    我们平时的工作中用到的Spring事务管理是管理一个数据源的.但是如果对多个数据源进行事务管理该怎么办呢?我们可以用JTA和Atomikos结合Spring来实现一个分布式事务管理的功能.了解JTA可 ...

随机推荐

  1. UI进阶 科大讯飞(2) 语音合成(文字转换成语音)

    科大讯飞开放平台.SDK下载.添加静态库.初始化见UI进阶 科大讯飞(1) 语音听写(语音转换成文字) 实现语音合成 功能实现步骤: 导入头文件 创建文字识别对象 指定文字识别后的回调代理对象 开启文 ...

  2. Linux syslog 学习

    最经有在看lighttpd facgi相关的东西.在lighttpd官网上看到如下sample code. #include <stdlib.h> #include <string. ...

  3. branch

    1.删除分支 git branch -d branch_name error: The branch 'branch_name' is not fully merged. If you are sur ...

  4. Unity3d:延迟加载ScrollView的内容

    问题描述:在一个scrollview中加载了大量的数据,有文字.图片.视频等等,首次加载的时候会很慢很卡,而且加载出来后,内存占用很大.解决方案1:思:固定一块区域,当物体滚动到这区域的时候再加载物体 ...

  5. iPhone中国移动收不到彩信,联通不用设置都可以,具体设置方法:

    打开“设置”. 打开“通用”. 打开“蜂窝移动网络”. 打开“蜂窝数据移动网络”. 在“蜂窝移动数据”一栏中的“APN”处填入“cmnet”. 在“彩信”一栏中的“APN”处填入“cmnet”,“MM ...

  6. 对.NET中Hashtable和ArryList的理解

    1.HashTabel 在.NET Framework中,Hashtable是System.Collections命名空间提供的集合对象,同时它也是一个可变长的数组,用于处理和表现类似key/valu ...

  7. Android操作联系人 android开发教程

    Android系统中的联系人也是通过ContentProvider来对外提供数据的,我们这里实现获取所有联系人.通过电话号码获取联系人.添加联系人.使用事务添加联系人. 获取所有联系人 1. Andr ...

  8. 【JSP】JSTL使用core标签总结(不断更新中)

    使用core标签 在页面中使用taglib指令指定标签URI和prefix.如: <%@ taglib uri="http://java.sun.com/jsp/jstl/core&q ...

  9. [Angular 2] Move and Delete Angular 2 Components After Creation

    After the original order is set, you can still leverage methods on the Angular 2 ViewContainer to re ...

  10. C语言待研究问题

    1.内存分配 变量的静态分配和静态变量的区别: 变量的静态分配和动态分配 2.堆和栈的区别 3.CPU的并发性 4.变量和参数的区别