【Java持久層】事務(wù)的傳播

傳播屬性 若當(dāng)前不存在事務(wù) 若當(dāng)前存在事務(wù)
REQUIRED 新建事務(wù) 使用當(dāng)前事務(wù)
REQUIRES_NEW 新建事務(wù) 掛起當(dāng)前事務(wù),新建事務(wù)
SUPPORTS 不使用事務(wù) 使用當(dāng)前事務(wù)
NOT_SUPPORTED 不使用事務(wù) 掛起當(dāng)前事務(wù)
MANDATORY 拋出異常 使用當(dāng)前事務(wù)
NEVER 不使用事務(wù) 拋出異常
NESTED 新建事務(wù) 開啟嵌套事務(wù)

源碼閱讀

TransactionInterceptor.invoke(...)
TransactionAspectSupport.invokeWithinTransaction(...) 
TransactionAspectSupport.createTransactionIfNecessary(...)
PlatformTransactionManager.getTransaction(...)
AbstractPlatformTransactionManager.getTransaction(...)
public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
    Object transaction = this.doGetTransaction();
    boolean debugEnabled = this.logger.isDebugEnabled();
    if (definition == null) {
        definition = new DefaultTransactionDefinition();
    }
    // 若存在事務(wù)
    if (this.isExistingTransaction(transaction)) {
        // 執(zhí)行存在事務(wù)的判斷邏輯
        return this.handleExistingTransaction((TransactionDefinition)definition, transaction, debugEnabled);
        // 若不存在事務(wù)
    } else if (((TransactionDefinition)definition).getTimeout() < -1) {
        throw new InvalidTimeoutException("Invalid transaction timeout", ((TransactionDefinition)definition).getTimeout());
        // int PROPAGATION_MANDATORY = 2
    } else if (((TransactionDefinition)definition).getPropagationBehavior() == 2) {
        throw new IllegalTransactionStateException("No existing transaction found for transaction marked with propagation 'mandatory'");
        // int PROPAGATION_REQUIRED = 0;int PROPAGATION_REQUIRES_NEW = 3;int PROPAGATION_NESTED = 6;
        // 非上述,則為PROPAGATION_SUPPORTS、PROPAGATION_NOT_SUPPORTED、PROPAGATION_NEVER
    } else if (((TransactionDefinition)definition).getPropagationBehavior() != 0 && ((TransactionDefinition)definition).getPropagationBehavior() != 3 && ((TransactionDefinition)definition).getPropagationBehavior() != 6) {
        if (((TransactionDefinition)definition).getIsolationLevel() != -1 && this.logger.isWarnEnabled()) {
            this.logger.warn("Custom isolation level specified but no actual transaction initiated; isolation level will effectively be ignored: " + definition);
        }

        boolean newSynchronization = this.getTransactionSynchronization() == 0;
        // 返回當(dāng)前(無事務(wù))狀態(tài)
        return this.prepareTransactionStatus((TransactionDefinition)definition, (Object)null, true, newSynchronization, debugEnabled, (Object)null);
    } else {
        // PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED
        AbstractPlatformTransactionManager.SuspendedResourcesHolder suspendedResources = this.suspend((Object)null);
        if (debugEnabled) {
            this.logger.debug("Creating new transaction with name [" + ((TransactionDefinition)definition).getName() + "]: " + definition);
        }

        try {
            boolean newSynchronization = this.getTransactionSynchronization() != 2;
            // 新建事務(wù)
            DefaultTransactionStatus status = this.newTransactionStatus((TransactionDefinition)definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
            this.doBegin(transaction, (TransactionDefinition)definition);
            this.prepareSynchronization(status, (TransactionDefinition)definition);
            return status;
        } catch (RuntimeException var7) {
            this.resume((Object)null, suspendedResources);
            throw var7;
        } catch (Error var8) {
            this.resume((Object)null, suspendedResources);
            throw var8;
        }
    }
}

// 當(dāng)前存在事務(wù)時的處理
private TransactionStatus handleExistingTransaction(TransactionDefinition definition, Object transaction, boolean debugEnabled) throws TransactionException {
    if (definition.getPropagationBehavior() == 5) {
        // int PROPAGATION_NEVER = 5;
        // 拋出異常
        throw new IllegalTransactionStateException("Existing transaction found for transaction marked with propagation 'never'");
    } else {
        AbstractPlatformTransactionManager.SuspendedResourcesHolder suspendedResources;
        boolean newSynchronization;
        if (definition.getPropagationBehavior() == 4) {
            // int PROPAGATION_NOT_SUPPORTED = 4;
            if (debugEnabled) {
                this.logger.debug("Suspending current transaction");
            }
            // 掛起當(dāng)前事務(wù)
            suspendedResources = this.suspend(transaction);
            newSynchronization = this.getTransactionSynchronization() == 0;
            // 返回?zé)o事務(wù)狀態(tài)
            return this.prepareTransactionStatus(definition, (Object)null, false, newSynchronization, debugEnabled, suspendedResources);
        } else if (definition.getPropagationBehavior() == 3) {
            // int PROPAGATION_REQUIRES_NEW = 3;
            if (debugEnabled) {
                this.logger.debug("Suspending current transaction, creating new transaction with name [" + definition.getName() + "]");
            }
            // 掛起當(dāng)前事務(wù)
            suspendedResources = this.suspend(transaction);

            try {
                newSynchronization = this.getTransactionSynchronization() != 2;
                DefaultTransactionStatus status = this.newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
                // 新建事務(wù)
                this.doBegin(transaction, definition);
                this.prepareSynchronization(status, definition);
                return status;
            } catch (RuntimeException var7) {
                this.resumeAfterBeginException(transaction, suspendedResources, var7);
                throw var7;
            } catch (Error var8) {
                this.resumeAfterBeginException(transaction, suspendedResources, var8);
                throw var8;
            }
        } else {
            boolean newSynchronization;
            if (definition.getPropagationBehavior() == 6) {
                // int PROPAGATION_NESTED = 6; 嵌套事務(wù)
                if (!this.isNestedTransactionAllowed()) {
                    throw new NestedTransactionNotSupportedException("Transaction manager does not allow nested transactions by default - specify 'nestedTransactionAllowed' property with value 'true'");
                } else {
                    if (debugEnabled) {
                        this.logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
                    }

                    if (this.useSavepointForNestedTransaction()) {
                        DefaultTransactionStatus status = this.prepareTransactionStatus(definition, transaction, false, false, debugEnabled, (Object)null);
                        status.createAndHoldSavepoint();
                        return status;
                    } else {
                        newSynchronization = this.getTransactionSynchronization() != 2;
                        DefaultTransactionStatus status = this.newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, (Object)null);
                        this.doBegin(transaction, definition);
                        this.prepareSynchronization(status, definition);
                        return status;
                    }
                }
            } else {
                if (debugEnabled) {
                    this.logger.debug("Participating in existing transaction");
                }
                // int PROPAGATION_REQUIRED = 0;int PROPAGATION_SUPPORTS = 1;int PROPAGATION_MANDATORY = 2;
                // 使用當(dāng)前事務(wù)

                if (this.isValidateExistingTransaction()) {
                    if (definition.getIsolationLevel() != -1) {
                        Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
                        if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
                            Constants isoConstants = DefaultTransactionDefinition.constants;
                            throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] specifies isolation level which is incompatible with existing transaction: " + (currentIsolationLevel != null ? isoConstants.toCode(currentIsolationLevel, "ISOLATION_") : "(unknown)"));
                        }
                    }

                    if (!definition.isReadOnly() && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                        throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] is not marked as read-only but existing transaction is");
                    }
                }

                newSynchronization = this.getTransactionSynchronization() != 2;
                return this.prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, (Object)null);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容