三、事务核心源码
咱们看一下核心类图:
如上提所示,PlatformTransactionManager顶级接口定义了最核心的事务管理方法,下面一层是AbstractPlatformTransactionManager抽象类,实现了PlatformTransactionManager接口的方法并定义了一些抽象方法,供子类拓展。最后下面一层是2个经典事务管理器:
1.DataSourceTransactionmanager,即JDBC单数据库事务管理器,基于Connection实现,
2.JtaTransactionManager,即多数据库事务管理器(又叫做分布式事务管理器),基于Session实现。
我们这里只看基于JDBC connection的DataSourceTransactionmanager源码。
PlatformTransactionManager接口:
1 public interface PlatformTransactionManager {2 // 获取事务状态3 TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;4 // 事务提交5 void commit(TransactionStatus status) throws TransactionException;6 // 事务回滚7 void rollback(TransactionStatus status) throws TransactionException;8 }
1. getTransaction获取事务
AbstractPlatformTransactionManager实现了getTransaction()方法如下:
1 @Override 2 public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { 3 Object transaction = doGetTransaction(); 4 5 // Cache debug flag to avoid repeated checks. 6 boolean debugEnabled = logger.isDebugEnabled(); 7 8 if (definition == null) { 9 // Use defaults if no transaction definition given.10 definition = new DefaultTransactionDefinition();11 }12 // 如果当前已经存在事务13 if (isExistingTransaction(transaction)) {14 // 根据不同传播机制不同处理15 return handleExistingTransaction(definition, transaction, debugEnabled);16 }17 18 // 超时不能小于默认值19 if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {20 throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());21 }22 23 // 当前不存在事务,传播机制=MANDATORY(支持当前事务,没事务报错),报错24 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {25 throw new IllegalTransactionStateException(26 "No existing transaction found for transaction marked with propagation 'mandatory'");27 }// 当前不存在事务,传播机制=REQUIRED/REQUIRED_NEW/NESTED,这三种情况,需要新开启事务,且加上事务同步28 else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||29 definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||30 definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {31 SuspendedResourcesHolder suspendedResources = suspend(null);32 if (debugEnabled) {33 logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);34 }35 try {// 是否需要新开启同步// 开启// 开启36 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);37 DefaultTransactionStatus status = newTransactionStatus(38 definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);39 doBegin(transaction, definition);// 开启新事务40 prepareSynchronization(status, definition);//预备同步41 return status;42 }43 catch (RuntimeException ex) {44 resume(null, suspendedResources);45 throw ex;46 }47 catch (Error err) {48 resume(null, suspendedResources);49 throw err;50 }51 }52 else {53 // 当前不存在事务当前不存在事务,且传播机制=PROPAGATION_SUPPORTS/PROPAGATION_NOT_SUPPORTED/PROPAGATION_NEVER,这三种情况,创建“空”事务:没有实际事务,但可能是同步。警告:定义了隔离级别,但并没有真实的事务初始化,隔离级别被忽略有隔离级别但是并没有定义实际的事务初始化,有隔离级别但是并没有定义实际的事务初始化,54 if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {55 logger.warn("Custom isolation level specified but no actual transaction initiated; " +56 "isolation level will effectively be ignored: " + definition);57 }58 boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);59 return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);60 }61 }
如上图,源码分成了2条处理线,
1.当前已存在事务:isExistingTransaction()判断是否存在事务,存在事务handleExistingTransaction()根据不同传播机制不同处理
2.当前不存在事务: 不同传播机制不同处理
handleExistingTransaction()源码如下:
1 private TransactionStatus handleExistingTransaction( 2 TransactionDefinition definition, Object transaction, boolean debugEnabled) 3 throws TransactionException { 4 // 1.NERVER(不支持当前事务;如果当前事务存在,抛出异常)报错 5 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) { 6 throw new IllegalTransactionStateException( 7 "Existing transaction found for transaction marked with propagation 'never'"); 8 } 9 // 2.NOT_SUPPORTED(不支持当前事务,现有同步将被挂起)挂起当前事务10 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {11 if (debugEnabled) {12 logger.debug("Suspending current transaction");13 }14 Object suspendedResources = suspend(transaction);15 boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);16 return prepareTransactionStatus(17 definition, null, false, newSynchronization, debugEnabled, suspendedResources);18 }19 // 3.REQUIRES_NEW挂起当前事务,创建新事务20 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {21 if (debugEnabled) {22 logger.debug("Suspending current transaction, creating new transaction with name [" +23 definition.getName() + "]");24 }// 挂起当前事务25 SuspendedResourcesHolder suspendedResources = suspend(transaction);26 try {// 创建新事务27 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);28 DefaultTransactionStatus status = newTransactionStatus(29 definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);30 doBegin(transaction, definition);31 prepareSynchronization(status, definition);32 return status;33 }34 catch (RuntimeException beginEx) {35 resumeAfterBeginException(transaction, suspendedResources, beginEx);36 throw beginEx;37 }38 catch (Error beginErr) {39 resumeAfterBeginException(transaction, suspendedResources, beginErr);40 throw beginErr;41 }42 }43 // 4.NESTED嵌套事务44 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {45 if (!isNestedTransactionAllowed()) {46 throw new NestedTransactionNotSupportedException(47 "Transaction manager does not allow nested transactions by default - " +48 "specify 'nestedTransactionAllowed' property with value 'true'");49 }50 if (debugEnabled) {51 logger.debug("Creating nested transaction with name [" + definition.getName() + "]");52 }// 是否支持保存点:非JTA事务走这个分支。AbstractPlatformTransactionManager默认是true,JtaTransactionManager复写了该方法false,DataSourceTransactionmanager没有复写,还是true,53 if (useSavepointForNestedTransaction()) { 54 // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.55 DefaultTransactionStatus status =56 prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);57 status.createAndHoldSavepoint();// 创建保存点58 return status;59 }60 else {61 // JTA事务走这个分支,创建新事务62 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);63 DefaultTransactionStatus status = newTransactionStatus(64 definition, transaction, true, newSynchronization, debugEnabled, null);65 doBegin(transaction, definition);66 prepareSynchronization(status, definition);67 return status;68 }69 }70 71 72 if (debugEnabled) {73 logger.debug("Participating in existing transaction");74 }75 if (isValidateExistingTransaction()) {76 if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {77 Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();78 if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {79 Constants isoConstants = DefaultTransactionDefinition.constants;80 throw new IllegalTransactionStateException("Participating transaction with definition [" +81 definition + "] specifies isolation level which is incompatible with existing transaction: " +82 (currentIsolationLevel != null ?83 isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :84 "(unknown)"));85 }86 }87 if (!definition.isReadOnly()) {88 if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {89 throw new IllegalTransactionStateException("Participating transaction with definition [" +90 definition + "] is not marked as read-only but existing transaction is");91 }92 }93 }// 到这里PROPAGATION_SUPPORTS 或 PROPAGATION_REQUIRED或PROPAGATION_MANDATORY,存在事务加入事务即可,prepareTransactionStatus第三个参数就是是否需要新事务。false代表不需要新事物94 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);95 return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);96 }
如上图,当前线程已存在事务情况下,新的不同隔离级别处理情况:
1.NERVER:不支持当前事务;如果当前事务存在,抛出异常:"Existing transaction found for transaction marked with propagation 'never'"
2.NOT_SUPPORTED:不支持当前事务,现有同步将被挂起:suspend()
3.REQUIRES_NEW挂起当前事务,创建新事务:
1)suspend()
2)doBegin()
4.NESTED嵌套事务
1)非JTA事务:createAndHoldSavepoint()创建JDBC3.0保存点,不需要同步
2) JTA事务:开启新事务,doBegin()+prepareSynchronization()需要同步
这里有几个核心方法:挂起当前事务suspend()、开启新事务doBegin()。
suspend()源码如下:
1 protected final SuspendedResourcesHolder suspend(Object transaction) throws TransactionException { 2 if (TransactionSynchronizationManager.isSynchronizationActive()) {// 1.当前存在同步, 3 List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization(); 4 try { 5 Object suspendedResources = null; 6 if (transaction != null) {// 事务不为空,挂起事务 7 suspendedResources = doSuspend(transaction); 8 }// 解除绑定当前事务各种属性:名称、只读、隔离级别、是否是真实的事务. 9 String name = TransactionSynchronizationManager.getCurrentTransactionName();10 TransactionSynchronizationManager.setCurrentTransactionName(null);11 boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();12 TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);13 Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();14 TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);15 boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();16 TransactionSynchronizationManager.setActualTransactionActive(false);17 return new SuspendedResourcesHolder(18 suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);19 }20 catch (RuntimeException ex) {21 // doSuspend failed - original transaction is still active...22 doResumeSynchronization(suspendedSynchronizations);23 throw ex;24 }25 catch (Error err) {26 // doSuspend failed - original transaction is still active...27 doResumeSynchronization(suspendedSynchronizations);28 throw err;29 }30 }// 2.没有同步但,事务不为空,挂起事务31 else if (transaction != null) {32 // Transaction active but no synchronization active.33 Object suspendedResources = doSuspend(transaction);34 return new SuspendedResourcesHolder(suspendedResources);35 }// 2.没有同步但,事务为空,什么都不用做36 else {37 // Neither transaction nor synchronization active.38 return null;39 }40 }
doSuspend(),挂起事务,AbstractPlatformTransactionManager抽象类doSuspend()会报错:不支持挂起,如果具体事务执行器支持就复写doSuspend(),DataSourceTransactionManager实现如下:
1 @Override2 protected Object doSuspend(Object transaction) {3 DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;4 txObject.setConnectionHolder(null);5 return TransactionSynchronizationManager.unbindResource(this.dataSource);6 }
挂起DataSourceTransactionManager事务的核心操作就是:
1.把当前事务的connectionHolder数据库连接持有者清空。
2.当前线程解绑datasource.其实就是ThreadLocal移除对应变量(TransactionSynchronizationManager类中定义的private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<Map<Object, Object>>("Transactional resources");)
TransactionSynchronizationManager事务同步管理器,该类维护了多个线程本地变量ThreadLocal,如下图:
1 public abstract class TransactionSynchronizationManager { 2 3 private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class); 4 // 事务资源:map<k,v> 两种数据对。1.会话工厂和会话k=SqlsessionFactory v=SqlSessionHolder 2.数据源和连接k=DataSource v=ConnectionHolder 5 private static final ThreadLocal<Map<Object, Object>> resources = 6 new NamedThreadLocal<Map<Object, Object>>("Transactional resources"); 7 // 事务同步 8 private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = 9 new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations");10 // 当前事务名称11 private static final ThreadLocal<String> currentTransactionName =12 new NamedThreadLocal<String>("Current transaction name");13 // 当前事务的只读属性14 private static final ThreadLocal<Boolean> currentTransactionReadOnly =15 new NamedThreadLocal<Boolean>("Current transaction read-only status");16 // 当前事务的隔离级别17 private static final ThreadLocal<Integer> currentTransactionIsolationLevel =18 new NamedThreadLocal<Integer>("Current transaction isolation level");19 // 是否存在事务20 private static final ThreadLocal<Boolean> actualTransactionActive =21 new NamedThreadLocal<Boolean>("Actual transaction active");22 。。。23 }
doBegin()源码如下:
1 @Override 2 protected void doBegin(Object transaction, TransactionDefinition definition) { 3 DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; 4 Connection con = null; 5 6 try {// 如果事务还没有connection或者connection在事务同步状态,重置新的connectionHolder 7 if (!txObject.hasConnectionHolder() || 8 txObject.getConnectionHolder().isSynchronizedWithTransaction()) { 9 Connection newCon = this.dataSource.getConnection();10 if (logger.isDebugEnabled()) {11 logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");12 }// 重置新的connectionHolder13 txObject.setConnectionHolder(new ConnectionHolder(newCon), true);14 }15 //设置新的连接为事务同步中16 txObject.getConnectionHolder().setSynchronizedWithTransaction(true);17 con = txObject.getConnectionHolder().getConnection();18 //conn设置事务隔离级别,只读19 Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);20 txObject.setPreviousIsolationLevel(previousIsolationLevel);//DataSourceTransactionObject设置事务隔离级别21 22 // 如果是自动提交切换到手动提交23 // so we don't want to do it unnecessarily (for example if we've explicitly24 // configured the connection pool to set it already).25 if (con.getAutoCommit()) {26 txObject.setMustRestoreAutoCommit(true);27 if (logger.isDebugEnabled()) {28 logger.debug("Switching JDBC Connection [" + con + "] to manual commit");29 }30 con.setAutoCommit(false);31 }32 // 如果只读,执行sql设置事务只读33 prepareTransactionalConnection(con, definition);34 txObject.getConnectionHolder().setTransactionActive(true);// 设置connection持有者的事务开启状态35 36 int timeout = determineTimeout(definition);37 if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {38 txObject.getConnectionHolder().setTimeoutInSeconds(timeout);// 设置超时秒数39 }40 41 // 绑定connection持有者到当前线程42 if (txObject.isNewConnectionHolder()) {43 TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());44 }45 }46 47 catch (Throwable ex) {48 if (txObject.isNewConnectionHolder()) {49 DataSourceUtils.releaseConnection(con, this.dataSource);50 txObject.setConnectionHolder(null, false);51 }52 throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);53 }54 }
如上图,开启新事务的准备工作doBegin()的核心操作就是:
1.DataSourceTransactionObject“数据源事务对象”,设置ConnectionHolder,再给ConnectionHolder设置各种属性:自动提交、超时、事务开启、隔离级别。
2.给当前线程绑定一个线程本地变量,key=DataSource数据源 v=ConnectionHolder数据库连接。
2. commit提交事务
讲解源码之前先看一下资源管理类:
一、SqlSessionSynchronization
是SqlSessionUtils的一个内部类,继承自TransactionSynchronizationAdapter抽象类,实现了事务同步接口TransactionSynchronization。
类图如下:
TransactionSynchronization接口定义了事务操作时的对应资源的(JDBC事务那么就是SqlSessionSynchronization)管理方法:
1 // 挂起事务 2 void suspend(); 3 // 唤醒事务 4 void resume(); 5 6 void flush(); 7 8 // 提交事务前 9 void beforeCommit(boolean readOnly);10 11 // 提交事务完成前12 void beforeCompletion();13 14 // 提交事务后15 void afterCommit();16 17 // 提交事务完成后18 void afterCompletion(int status);
二、commit
AbstractPlatformTransactionManager的commit源码如下:
1 @Override 2 public final void commit(TransactionStatus status) throws TransactionException { 3 if (status.isCompleted()) {// 如果事务已完结,报错无法再次提交 4 throw new IllegalTransactionStateException( 5 "Transaction is already completed - do not call commit or rollback more than once per transaction"); 6 } 7 8 DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status; 9 if (defStatus.isLocalRollbackOnly()) {// 如果事务明确标记为回滚,10 if (defStatus.isDebug()) {11 logger.debug("Transactional code has requested rollback");12 }13 processRollback(defStatus);//执行回滚14 return;15 }//如果不需要全局回滚时提交 且 全局回滚16 if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {17 if (defStatus.isDebug()) {18 logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");19 }//执行回滚20 processRollback(defStatus);21 // 仅在最外层事务边界(新事务)或显式地请求时抛出“未期望的回滚异常”23 if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {24 throw new UnexpectedRollbackException(25 "Transaction rolled back because it has been marked as rollback-only");26 }27 return;28 }29 // 执行提交事务30 processCommit(defStatus);31 }
如上图,各种判断:
1.如果事务明确标记为本地回滚,-》执行回滚
2.如果不需要全局回滚时提交 且 全局回滚-》执行回滚
3.提交事务,核心方法processCommit()
processCommit如下:
1 private void processCommit(DefaultTransactionStatus status) throws TransactionException { 2 try { 3 boolean beforeCompletionInvoked = false; 4 try {//3个前置操作 5 prepareForCommit(status); 6 triggerBeforeCommit(status); 7 triggerBeforeCompletion(status); 8 beforeCompletionInvoked = true;//3个前置操作已调用 9 boolean globalRollbackOnly = false;//新事务 或 全局回滚失败10 if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {11 globalRollbackOnly = status.isGlobalRollbackOnly();12 }//1.有保存点,即嵌套事务13 if (status.hasSavepoint()) {14 if (status.isDebug()) {15 logger.debug("Releasing transaction savepoint");16 }//释放保存点17 status.releaseHeldSavepoint();18 }//2.新事务19 else if (status.isNewTransaction()) {20 if (status.isDebug()) {21 logger.debug("Initiating transaction commit");22 }//调用事务处理器提交事务23 doCommit(status);24 }25 // 3.非新事务,且全局回滚失败,但是提交时没有得到异常,抛出异常27 if (globalRollbackOnly) {28 throw new UnexpectedRollbackException(29 "Transaction silently rolled back because it has been marked as rollback-only");30 }31 }32 catch (UnexpectedRollbackException ex) {33 // 触发完成后事务同步,状态为回滚34 triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);35 throw ex;36 }// 事务异常37 catch (TransactionException ex) {38 // 提交失败回滚39 if (isRollbackOnCommitFailure()) {40 doRollbackOnCommitException(status, ex);41 }// 触发完成后回调,事务同步状态为未知42 else {43 triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);44 }45 throw ex;46 }// 运行时异常47 catch (RuntimeException ex) { // 如果3个前置步骤未完成,调用前置的最后一步操作48 if (!beforeCompletionInvoked) {49 triggerBeforeCompletion(status);50 }// 提交异常回滚51 doRollbackOnCommitException(status, ex);52 throw ex;53 }// 其它异常54 catch (Error err) { // 如果3个前置步骤未完成,调用前置的最后一步操作55 if (!beforeCompletionInvoked) {56 triggerBeforeCompletion(status);57 }// 提交异常回滚58 doRollbackOnCommitException(status, err);59 throw err;60 }61 62 // Trigger afterCommit callbacks, with an exception thrown there63 // propagated to callers but the transaction still considered as committed.64 try {65 triggerAfterCommit(status);66 }67 finally {68 triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);69 }70 71 }72 finally {73 cleanupAfterCompletion(status);74 }75 }
如上图,commit事务时,有6个核心操作,分别是3个前置操作,3个后置操作,如下:
1.prepareForCommit(status);源码是空的,没有拓展目前。
2.triggerBeforeCommit(status); 提交前触发操作
1 protected final void triggerBeforeCommit(DefaultTransactionStatus status) {2 if (status.isNewSynchronization()) {3 if (status.isDebug()) {4 logger.trace("Triggering beforeCommit synchronization");5 }6 TransactionSynchronizationUtils.triggerBeforeCommit(status.isReadOnly());7 }8 }
triggerBeforeCommit源码如下:
1 public static void triggerBeforeCommit(boolean readOnly) {2 for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) {3 synchronization.beforeCommit(readOnly);4 }5 }
如上图,TransactionSynchronizationManager类定义了多个ThreadLocal(线程本地变量),其中一个用以保存当前线程的事务同步:
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations");
遍历事务同步器,把每个事务同步器都执行“提交前”操作,比如咱们用的jdbc事务,那么最终就是SqlSessionUtils.beforeCommit()->this.holder.getSqlSession().commit();提交会话。
3.triggerBeforeCompletion(status);完成前触发操作,如果是jdbc事务,那么最终就是
SqlSessionUtils.beforeCompletion->
TransactionSynchronizationManager.unbindResource(sessionFactory); 解绑当前线程的会话工厂
this.holder.getSqlSession().close();关闭会话。
4.triggerAfterCommit(status);提交事务后触发操作。TransactionSynchronizationUtils.triggerAfterCommit();->TransactionSynchronizationUtils.invokeAfterCommit,如下:
1 public static void invokeAfterCommit(List<TransactionSynchronization> synchronizations) {2 if (synchronizations != null) {3 for (TransactionSynchronization synchronization : synchronizations) {4 synchronization.afterCommit();5 }6 }7 }
好吧,一顿找,最后在TransactionSynchronizationAdapter中复写过,并且是空的....SqlSessionSynchronization继承了TransactionSynchronizationAdapter但是没有复写这个方法。
5. triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
TransactionSynchronizationUtils.TransactionSynchronizationUtils.invokeAfterCompletion,如下:
1 public static void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) { 2 if (synchronizations != null) { 3 for (TransactionSynchronization synchronization : synchronizations) { 4 try { 5 synchronization.afterCompletion(completionStatus); 6 } 7 catch (Throwable tsex) { 8 logger.error("TransactionSynchronization.afterCompletion threw exception", tsex); 9 }10 }11 }12 }
afterCompletion:对于JDBC事务来说,最终:
1)如果会话任然活着,关闭会话,
2)重置各种属性:SQL会话同步器(SqlSessionSynchronization)的SQL会话持有者(SqlSessionHolder)的referenceCount引用计数、synchronizedWithTransaction同步事务、rollbackOnly只回滚、deadline超时时间点。
6.cleanupAfterCompletion(status);
1)设置事务状态为已完成。
2) 如果是新的事务同步,解绑当前线程绑定的数据库资源,重置数据库连接
3)如果存在挂起的事务(嵌套事务),唤醒挂起的老事务的各种资源:数据库资源、同步器。
1 private void cleanupAfterCompletion(DefaultTransactionStatus status) { 2 status.setCompleted();//设置事务状态完成 //如果是新的同步,清空当前线程绑定的除了资源外的全部线程本地变量:包括事务同步器、事务名称、只读属性、隔离级别、真实的事务激活状态 3 if (status.isNewSynchronization()) { 4 TransactionSynchronizationManager.clear(); 5 }//如果是新的事务同步 6 if (status.isNewTransaction()) { 7 doCleanupAfterCompletion(status.getTransaction()); 8 }//如果存在挂起的资源 9 if (status.getSuspendedResources() != null) {10 if (status.isDebug()) {11 logger.debug("Resuming suspended transaction after completion of inner transaction");12 }//唤醒挂起的事务和资源(重新绑定之前挂起的数据库资源,唤醒同步器,注册同步器到TransactionSynchronizationManager)13 resume(status.getTransaction(), (SuspendedResourcesHolder) status.getSuspendedResources());14 }15 }
对于DataSourceTransactionManager,doCleanupAfterCompletion源码如下:
1 protected void doCleanupAfterCompletion(Object transaction) { 2 DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; 3 4 // 如果是最新的连接持有者,解绑当前线程绑定的<数据库资源,ConnectionHolder> 5 if (txObject.isNewConnectionHolder()) { 6 TransactionSynchronizationManager.unbindResource(this.dataSource); 7 } 8 9 // 重置数据库连接(隔离级别、只读)10 Connection con = txObject.getConnectionHolder().getConnection();11 try {12 if (txObject.isMustRestoreAutoCommit()) {13 con.setAutoCommit(true);14 }15 DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());16 }17 catch (Throwable ex) {18 logger.debug("Could not reset JDBC Connection after transaction", ex);19 }20 21 if (txObject.isNewConnectionHolder()) {22 if (logger.isDebugEnabled()) {23 logger.debug("Releasing JDBC Connection [" + con + "] after transaction");24 }// 资源引用计数-1,关闭数据库连接25 DataSourceUtils.releaseConnection(con, this.dataSource);26 }27 // 重置连接持有者的全部属性28 txObject.getConnectionHolder().clear();29 }
3. rollback回滚事务
AbstractPlatformTransactionManager中rollback源码如下:
1 public final void rollback(TransactionStatus status) throws TransactionException {2 if (status.isCompleted()) {3 throw new IllegalTransactionStateException(4 "Transaction is already completed - do not call commit or rollback more than once per transaction");5 }6 7 DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;8 processRollback(defStatus);9 }
processRollback源码如下:
1 private void processRollback(DefaultTransactionStatus status) { 2 try { 3 try {// 解绑当前线程绑定的会话工厂,并关闭会话 4 triggerBeforeCompletion(status); 5 if (status.hasSavepoint()) {// 1.如果有保存点,即嵌套式事务 6 if (status.isDebug()) { 7 logger.debug("Rolling back transaction to savepoint"); 8 }//回滚到保存点 9 status.rollbackToHeldSavepoint();10 }//2.如果就是一个简单事务11 else if (status.isNewTransaction()) {12 if (status.isDebug()) {13 logger.debug("Initiating transaction rollback");14 }//回滚核心方法15 doRollback(status);16 }//3.当前存在事务且没有保存点,即加入当前事务的17 else if (status.hasTransaction()) {//如果已经标记为回滚 或 当加入事务失败时全局回滚(默认true)18 if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {19 if (status.isDebug()) {//debug时会打印:加入事务失败-标记已存在事务为回滚20 logger.debug("Participating transaction failed - marking existing transaction as rollback-only");21 }//设置当前connectionHolder:当加入一个已存在事务时回滚22 doSetRollbackOnly(status);23 }24 else {25 if (status.isDebug()) {26 logger.debug("Participating transaction failed - letting transaction originator decide on rollback");27 }28 }29 }30 else {31 logger.debug("Should roll back transaction but cannot - no transaction available");32 }33 }34 catch (RuntimeException ex) {//关闭会话,重置SqlSessionHolder属性35 triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);36 throw ex;37 }38 catch (Error err) {39 triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);40 throw err;41 }42 triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);43 }44 finally {、、解绑当前线程45 cleanupAfterCompletion(status);46 }47 }
如上图,有几个公共方法和提交事务时一致,就不再重复。
这里主要看doRollback,DataSourceTransactionManager的doRollback()源码如下:
1 protected void doRollback(DefaultTransactionStatus status) { 2 DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction(); 3 Connection con = txObject.getConnectionHolder().getConnection(); 4 if (status.isDebug()) { 5 logger.debug("Rolling back JDBC transaction on Connection [" + con + "]"); 6 } 7 try { 8 con.rollback(); 9 }10 catch (SQLException ex) {11 throw new TransactionSystemException("Could not roll back JDBC transaction", ex);12 }13 }
好吧,一点不复杂,就是Connection的rollback.
四、时序图
特地整理了时序图(简单的新事务,没有画出连接点等情况)如下:
===========参考========
《Spring实战4》第四章 面向切面的Spring
原文出处:https://www.cnblogs.com/dennyzhangdd/p/9602673.html