Spring官方並無提供對MyBatis的集成方案,因而MyBatis項目組本身寫了一個項目mybatis-spring專門用於在spring中使用MyBatis。java
mybatis-spring的實現很大程度上依賴spring jdbc的事務管理,因此咱們先看一下在spring中直接使用jdbc訪問數據庫時是如何處理事務的。不管你是使用@Transactional註解這樣的AOP配置方式,仍是TransactionTemplate這樣的編碼方式,最終執行的操做事務的代碼都會是相似下面這樣git
DefaultTransactionDefinition def = new DefaultTransactionDefinition(); PlatformTransactionManager txManager = new DataSourceTransactionManager(dataSource); TransactionStatus status = txManager.getTransaction(def); try { //get jdbc connection... //execute sql... txManager.commit(status); } catch (Exception e) { txManager.rollback(status); throw e; }
能夠看到PlatformTransactionManager的getTransaction(), rollback(), commit()是spring處理事務的核心api,分別對應事務的開始,提交和回滾。github
spring事務處理的一個關鍵是保證在整個事務的生命週期裏全部執行sql的jdbc connection和處理事務的jdbc connection始終是同一個。而後執行sql的業務代碼通常都分散在程序的不一樣地方,如何讓它們共享一個jdbc connection呢?這裏spring作了一個前提假設:即一個事務的操做必定是在一個thread中執行,且一個thread中若是有多個不一樣jdbc connection生成的事務的話,他們必須順序執行,不能同時存在。(這個假設在絕大多數狀況下都是成立的)。基於這個假設,spring在transaction建立時,會用ThreadLocal把建立這個事務的jdbc connection綁定到當前thread,接下來在事務的整個生命週期中都會從ThreadLocal中獲取同一個jdbc connection。spring
咱們看一下詳細調用過程sql
對spring jdbc的事務處理有了瞭解後,咱們來看mybatis是如何經過spring處理事務的。數據庫
先看一下配置apache
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionFactory"> <bean class="org.apache.ibatis.spring.transaction.SpringManagedTransactionFactory" /> </property> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean>
而後看其調用過程api
能夠看到mybatis-spring處理事務的主要流程和spring jdbc處理事務並無什麼區別,都是經過DataSourceTransactionManager的getTransaction(), rollback(), commit()完成事務的生命週期管理,並且jdbc connection的建立也是經過DataSourceTransactionManager.getTransaction()完成,mybatis並無參與其中,mybatis只是在執行sql時經過DataSourceUtils.getConnection()得到當前thread的jdbc connection,而後在其上執行sql。緩存
下面結合代碼來看session
<SqlSessionUtils>: public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED); notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); SqlSession session = sessionHolder(executorType, holder); if (session != null) { return session; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating a new SqlSession"); } session = sessionFactory.openSession(executorType); registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session); return session; } private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator, SqlSession session) { SqlSessionHolder holder; if (TransactionSynchronizationManager.isSynchronizationActive()) { Environment environment = sessionFactory.getConfiguration().getEnvironment(); if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator); TransactionSynchronizationManager.bindResource(sessionFactory, holder); TransactionSynchronizationManager.registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory)); holder.setSynchronizedWithTransaction(true); holder.requested(); } else { if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SqlSession [" + session + "] was not registered for synchronization because DataSource is not transactional"); } } else { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } }
執行sql時調用sqlSessionTemplate的insert,update,delete方法,sqlSessionTemplate是DefaultSqlSession的一個代理類,它經過SqlSessionUtils.getSqlSession()試圖從ThreadLocal獲取當前事務所使用的SqlSession。若是是第一次獲取時會調用SqlSessionFactory.openSession()建立一個SqlSession並綁定到ThreadLocal,同時還會經過TransactionSynchronizationManager註冊一個SqlSessionSynchronization。
<SqlSessionSynchronization>: public void beforeCommit(boolean readOnly) { // Connection commit or rollback will be handled by ConnectionSynchronization or // DataSourceTransactionManager. // But, do cleanup the SqlSession / Executor, including flushing BATCH statements so // they are actually executed. // SpringManagedTransaction will no-op the commit over the jdbc connection // TODO This updates 2nd level caches but the tx may be rolledback later on! if (TransactionSynchronizationManager.isActualTransactionActive()) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Transaction synchronization committing SqlSession [" + this.holder.getSqlSession() + "]"); } this.holder.getSqlSession().commit(); } catch (PersistenceException p) { if (this.holder.getPersistenceExceptionTranslator() != null) { DataAccessException translated = this.holder .getPersistenceExceptionTranslator() .translateExceptionIfPossible(p); if (translated != null) { throw translated; } } throw p; } }
SqlSessionSynchronization是一個事務生命週期的callback接口,mybatis-spring經過SqlSessionSynchronization在事務提交和回滾前分別調用DefaultSqlSession.commit()和DefaultSqlSession.rollback()
<BaseExecutor>: public void commit(boolean required) throws SQLException { if (closed) throw new ExecutorException("Cannot commit, transaction is already closed"); clearLocalCache(); flushStatements(); if (required) { transaction.commit(); } } public void rollback(boolean required) throws SQLException { if (!closed) { try { clearLocalCache(); flushStatements(true); } finally { if (required) { transaction.rollback(); } } } } public void clearLocalCache() { if (!closed) { localCache.clear(); localOutputParameterCache.clear(); } }
<SpringManagedTransaction>: this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource); public void commit() throws SQLException { if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Committing JDBC Connection [" + this.connection + "]"); } this.connection.commit(); } } public void rollback() throws SQLException { if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rolling back JDBC Connection [" + this.connection + "]"); } this.connection.rollback(); } }
<DataSourceUtils>: /** * Determine whether the given JDBC Connection is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param con the Connection to check * @param dataSource the DataSource that the Connection was obtained from * (may be {@code null}) * @return whether the Connection is transactional */ public static boolean isConnectionTransactional(Connection con, DataSource dataSource) { if (dataSource == null) { return false; } ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource); return (conHolder != null && connectionEquals(conHolder, con)); }
這裏的DefaultSqlSession只會進行一些自身緩存的清理工做,並不會真正提交事務給數據庫,緣由是這裏的DefaultSqlSession使用的Transaction實現爲SpringManagedTransaction,SpringManagedTransaction在提交事務前會檢查當前事務是否應該由spring控制,若是是,則不會本身提交事務,而將提交事務的任務交給spring,因此DefaultSqlSession並不會本身處理事務。
<SpringManagedTransaction>: public Connection getConnection() throws SQLException { if (this.connection == null) { openConnection(); } return this.connection; } /** * Gets a connection from Spring transaction manager and discovers if this * {@code Transaction} should manage connection or let it to Spring. * <p> * It also reads autocommit setting because when using Spring Transaction MyBatis * thinks that autocommit is always false and will always call commit/rollback * so we need to no-op that calls. */ 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 (LOGGER.isDebugEnabled()) { LOGGER.debug( "JDBC Connection [" + this.connection + "] will" + (this.isConnectionTransactional ? " " : " not ") + "be managed by Spring"); } }
DefaultSqlSession執行sql時,會經過SpringManagedTransaction調用DataSourceUtils.getConnection()從ThreadLocal中獲取jdbc connection並在其上執行sql。
總結:mybatis-spring處理事務的主要流程和spring jdbc處理事務並無什麼區別,都是經過DataSourceTransactionManager的getTransaction(), rollback(), commit()完成事務的生命週期管理,並且jdbc connection的建立也是經過DataSourceTransactionManager.getTransaction()完成,mybatis並無參與其中,mybatis只是在執行sql時經過DataSourceUtils.getConnection()得到當前thread的jdbc connection,而後在其上執行sql。
mybatis-spring作的最主要的事情是: