1 概述
在Spring事務(wù)中栈幸,我們可以配置事務(wù)的傳播屬性瞪讼,傳播屬性的處理在函數(shù)AbstractPlatformTransactionManager.handleExistingTransaction
中楼入,具體可參考源碼磷仰。關(guān)于Spring中傳播屬性的定義可見(jiàn)其官方文檔Transaction Propagation姆蘸,對(duì)于本文介紹的PROPAGATION_NESTED暴氏,Spring官方文檔描述如下:
PROPAGATION_NESTED
uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks let an inner transaction scope trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. This setting is typically mapped onto JDBC savepoints, so it works only with JDBC resource transactions. See Spring’sDataSourceTransactionManager
.
可見(jiàn)祝蝠,Spring采用一個(gè)物理事務(wù)音诈,但是結(jié)合著savepoint機(jī)制(MySql中稱為保存點(diǎn))實(shí)現(xiàn)一個(gè)事務(wù)中的指定范圍提交幻碱。
2 保存點(diǎn)創(chuàng)建準(zhǔn)備
Spring如何使用AOP實(shí)現(xiàn)事務(wù)控制的邏輯這里不去詳細(xì)介紹,我們通過(guò)源碼追蹤可以發(fā)現(xiàn)調(diào)用軌跡如下:
TransactionInterceptor.invoke
->
TransactionAspectSupport.invokeWithinTransaction
->
TransactionAspectSupport.createTransactionIfNecessary
->
AbstractPlatformTransactionManager.getTransaction
->
AbstractPlatformTransactionManager.doGetTransaction
->
這里我們看AbstractPlatformTransactionManager
子類(lèi)DataSourceTransactionManager.doGetTransaction
實(shí)現(xiàn)
繼續(xù)上面的過(guò)程:
//DataSourceTransactionManager
@Override
protected Object doGetTransaction() {
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
//看下方列出的DataSourceTransactionManager構(gòu)造函數(shù)细溅,
//isNestedTransactionAllowed會(huì)返回true
//就是默認(rèn)支持嵌套事務(wù)
//而嵌套事務(wù)又是采用savepoint實(shí)現(xiàn)的
txObject.setSavepointAllowed(isNestedTransactionAllowed());
ConnectionHolder conHolder =
(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
txObject.setConnectionHolder(conHolder, false);
return txObject;
}
/**
* Create a new DataSourceTransactionManager instance.
* A DataSource has to be set to be able to use it.
* @see #setDataSource
*/
public DataSourceTransactionManager() {
setNestedTransactionAllowed(true);
}
上面已經(jīng)介紹了褥傍,如果支持嵌套事務(wù),則創(chuàng)建的DataSourceTransactionObject.isSavepointAllowed
會(huì)被設(shè)為true
喇聊。
3 保存點(diǎn)創(chuàng)建
在第一章概述中說(shuō)到恍风,如果傳播屬性設(shè)為PROPAGATION_NESTED,如果創(chuàng)建事務(wù)時(shí)已經(jīng)存在了一個(gè)事務(wù)誓篱,則會(huì)創(chuàng)建一個(gè)嵌套事務(wù):
//AbstractPlatformTransactionManager
//省略其他不相關(guān)代碼
/**
* Create a TransactionStatus for an existing transaction.
*/
private TransactionStatus handleExistingTransaction(
TransactionDefinition definition, Object transaction, boolean debugEnabled)
throws TransactionException {
...
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
//如果當(dāng)前TransactionManager不支持嵌套事務(wù)
//直接拋錯(cuò)
if (!isNestedTransactionAllowed()) {
throw new NestedTransactionNotSupportedException(
"Transaction manager does not allow nested transactions by default - " +
"specify 'nestedTransactionAllowed' property with value 'true'");
}
if (debugEnabled) {
logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
}
//判斷當(dāng)前TransactionManager實(shí)現(xiàn)是否是采用保存點(diǎn)實(shí)現(xiàn)嵌套事務(wù)
if (useSavepointForNestedTransaction()) {
// Create savepoint within existing Spring-managed transaction,
// through the SavepointManager API implemented by TransactionStatus.
// Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
//創(chuàng)建保存點(diǎn)
status.createAndHoldSavepoint();
return status;
}
else {
//使用嵌套的begin朋贬、commit/rollback實(shí)現(xiàn)嵌套事務(wù),MySql
//不支持窜骄,因?yàn)槿绻呀?jīng)調(diào)用過(guò)begin锦募,提交之前再調(diào)用
//begin操作,MySql會(huì)隱式調(diào)用一次commit邻遏,不能達(dá)到嵌套事務(wù)
//的效果糠亩,這種方式某些數(shù)據(jù)庫(kù)可能會(huì)支持,這里不做介紹
// Nested transaction through nested begin and commit/rollback calls.
// Usually only for JTA: Spring synchronization might get activated here
// in case of a pre-existing JTA transaction.
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, null);
doBegin(transaction, definition);
prepareSynchronization(status, definition);
return status;
}
}
...
}
上面關(guān)于MySql begin操作隱式進(jìn)行提交可參考其官方描述Statements That Cause an Implicit Commit
DefaultTransactionStatus.createAndHoldSavepoint
在其父類(lèi)AbstractTransactionStatus
實(shí)現(xiàn):
//AbstractTransactionStatus
//具體怎么創(chuàng)建的不再展開(kāi)准验,可以自行查看代碼
/**
* Create a savepoint and hold it for the transaction.
* @throws org.springframework.transaction.NestedTransactionNotSupportedException
* if the underlying transaction does not support savepoints
*/
public void createAndHoldSavepoint() throws TransactionException {
setSavepoint(getSavepointManager().createSavepoint());
}
DefaultTransactionStatus
創(chuàng)建保存點(diǎn)之后同時(shí)會(huì)保存該保存點(diǎn)赎线,也就是上面setSavepoint
的調(diào)用。
4 保存點(diǎn)提交或釋放
4.1 保存點(diǎn)提交
在事務(wù)完成之后沟娱,會(huì)進(jìn)行事務(wù)提交氛驮,具體的會(huì)調(diào)用AbstractPlatformTransactionManager.commit
//AbstractPlatformTransactionManager
/**
* This implementation of commit handles participating in existing
* transactions and programmatic rollback requests.
* Delegates to {@code isRollbackOnly}, {@code doCommit}
* and {@code rollback}.
* @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
* @see #doCommit
* @see #rollback
*/
@Override
public final void commit(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
processRollback(defStatus, false);
return;
}
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus, true);
return;
}
processCommit(defStatus);
}
我們先看正常提交processCommit
:
//AbstractPlatformTransactionManager
/**
* Process an actual commit.
* Rollback-only flags have already been checked and applied.
* @param status object representing the transaction
* @throws TransactionException in case of commit failure
*/
private void processCommit(DefaultTransactionStatus status) throws TransactionException {
try {
boolean beforeCompletionInvoked = false;
try {
boolean unexpectedRollback = false;
prepareForCommit(status);
triggerBeforeCommit(status);
triggerBeforeCompletion(status);
beforeCompletionInvoked = true;
//如果當(dāng)前status有保存點(diǎn),表示當(dāng)前提交的是嵌套在某個(gè)事務(wù)
//內(nèi)的子事務(wù)济似,通過(guò)釋放保存點(diǎn)提交
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Releasing transaction savepoint");
}
unexpectedRollback = status.isGlobalRollbackOnly();
//釋放保存的保存點(diǎn)
status.releaseHeldSavepoint();
}//else表示通過(guò)begin矫废、commit/rollback實(shí)現(xiàn)子事務(wù),這里不介紹
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction commit");
}
unexpectedRollback = status.isGlobalRollbackOnly();
doCommit(status);
}
else if (isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = status.isGlobalRollbackOnly();
}
// Throw UnexpectedRollbackException if we have a global rollback-only
// marker but still didn't get a corresponding exception from commit.
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction silently rolled back because it has been marked as rollback-only");
}
}
catch (UnexpectedRollbackException ex) {
// can only be caused by doCommit
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
throw ex;
}
catch (TransactionException ex) {
// can only be caused by doCommit
if (isRollbackOnCommitFailure()) {
doRollbackOnCommitException(status, ex);
}
else {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
}
throw ex;
}
catch (RuntimeException | Error ex) {
if (!beforeCompletionInvoked) {
triggerBeforeCompletion(status);
}
doRollbackOnCommitException(status, ex);
throw ex;
}
// Trigger afterCommit callbacks, with an exception thrown there
// propagated to callers but the transaction still considered as committed.
try {
triggerAfterCommit(status);
}
finally {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
}
}
finally {
cleanupAfterCompletion(status);
}
}
4.2 保存點(diǎn)釋放
發(fā)生異常時(shí)的回滾操作實(shí)現(xiàn)如下:
//AbstractPlatformTransactionManager
/**
* Process an actual rollback.
* The completed flag has already been checked.
* @param status object representing the transaction
* @throws TransactionException in case of rollback failure
*/
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
triggerBeforeCompletion(status);
//如果有保存點(diǎn)砰蠢,同樣是對(duì)當(dāng)前保存點(diǎn)進(jìn)行回滾蓖扑,
//依此達(dá)到部分回滾的功能
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
}
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
doRollback(status);
}
else {
// Participating in larger transaction
if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
}
doSetRollbackOnly(status);
}
else {
if (status.isDebug()) {
logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
}
}
}
else {
logger.debug("Should roll back transaction but cannot - no transaction available");
}
// Unexpected rollback only matters here if we're asked to fail early
if (!isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = false;
}
}
}
catch (RuntimeException | Error ex) {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
throw ex;
}
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
// Raise UnexpectedRollbackException if we had a global rollback-only marker
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
}
finally {
cleanupAfterCompletion(status);
}
}