美文网首页
【Java持久层】事务的传播

【Java持久层】事务的传播

作者: Children乏 | 来源:发表于2020-02-06 17:33 被阅读0次
    传播属性 若当前不存在事务 若当前存在事务
    REQUIRED 新建事务 使用当前事务
    REQUIRES_NEW 新建事务 挂起当前事务,新建事务
    SUPPORTS 不使用事务 使用当前事务
    NOT_SUPPORTED 不使用事务 挂起当前事务
    MANDATORY 抛出异常 使用当前事务
    NEVER 不使用事务 抛出异常
    NESTED 新建事务 开启嵌套事务

    源码阅读

    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();
        }
        // 若存在事务
        if (this.isExistingTransaction(transaction)) {
            // 执行存在事务的判断逻辑
            return this.handleExistingTransaction((TransactionDefinition)definition, transaction, debugEnabled);
            // 若不存在事务
        } 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;
            // 返回当前(无事务)状态
            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;
                // 新建事务
                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;
            }
        }
    }
    
    // 当前存在事务时的处理
    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");
                }
                // 挂起当前事务
                suspendedResources = this.suspend(transaction);
                newSynchronization = this.getTransactionSynchronization() == 0;
                // 返回无事务状态
                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() + "]");
                }
                // 挂起当前事务
                suspendedResources = this.suspend(transaction);
    
                try {
                    newSynchronization = this.getTransactionSynchronization() != 2;
                    DefaultTransactionStatus status = this.newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
                    // 新建事务
                    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; 嵌套事务
                    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;
                    // 使用当前事务
    
                    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);
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:【Java持久层】事务的传播

          本文链接:https://www.haomeiwen.com/subject/svsuxhtx.html