美文网首页
【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持久层】事务的传播

    传播属性若当前不存在事务若当前存在事务REQUIRED新建事务使用当前事务REQUIRES_NEW新建事务挂起当前...

  • java 小结

    表现层web-mvc模式 业务层 持久层dao-orm映射 设计原则: java 事务 transaction 架...

  • spring 事务的七种传播机制与四种隔离级别

    一. spring 事务的七种传播机制 事务传播行为是为了解决业务层方法之间互相调用的事务问题. 1. PROPA...

  • 【spring0】SQL

    JPA(Java Persistence API):Java持久层APIJPA 和 Hibernate 有哪些区别...

  • Spring从入门到入土——Spring整合JPA

    1、jpa入门 Java持久层api,替代jdbc,Java持久化规范。JPA是Hibernate的一个抽象,是一...

  • spring boot 整合持久层jdbc

    Spring boot 整合持久层 持久层是Java EE中访问数据库的核心操作,Spring boot中对常见的...

  • 大话Java持久层

    基础知识储备: Java SE(Java语言【java.lang】、Java集合框架【java.util】) Ja...

  • Tangyuan介绍

    tangyuan 1. 项目介绍 TangYuan是一个基于Java的持久层框架。提供的持久层框架包括SQL Ma...

  • hibernate体系结构

    Hibernate包括很多对象持久对象,会话工厂、事务工厂、链接工厂、会话、事务等。Hibernate中有4层:J...

  • MyBatis

    MyBatis MyBatis,是一个基于Java的持久层框架。持久层: 可以将业务数据存储到磁盘,具备长期存储能...

网友评论

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

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