Spring事务框架之TransactionDefinition源码解析

 更新时间:2023年08月29日 11:52:25   作者:福  
这篇文章主要为大家介绍了Spring事务框架之TransactionDefinition源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

Spring事务的底层原理

  • Spring事务的框架。
  • Spring事务引入机制,主要学习@EnableTransactionManagement的相关内容。
  • Spring事务的控制机制,主要学习@Trasactional相关内容。

先从Spring事务的框架开始。

Spring事务框架中最重要的内容主要包括:

  • 事务管理器TransactionManager。
  • 事务定义TransactionDefinition。
  • 事务状态TransactionStatus。

其中事务管理器是核心,研究事务管理器需要用到TransactionDefinition和TransactionStatus,所以我们先研究这两部分。

TransactionDefinition

顾名思义,TransactionDefinition是用来定义事务属性的。

有两个比较重要的实现类,一个是DefaultTransactionAttribute.

另一个是DefaultTransactionTemplate:

下来看一下TransactionDefinition中定义的几个事务属性:

事务传播机制,7个事务传播机制的具体含义,我们在其他文章中已经分析过了:

int PROPAGATION_REQUIRED = 0;
int PROPAGATION_SUPPORTS = 1;
int PROPAGATION_MANDATORY = 2;
int PROPAGATION_REQUIRES_NEW = 3;
int PROPAGATION_NOT_SUPPORTED = 4;
int PROPAGATION_NEVER = 5;
int PROPAGATION_NESTED = 6;

隔离级别

数据库隔离级别:

//数据库的默认隔离级别
int ISOLATION_DEFAULT = -1;
int ISOLATION_READ_UNCOMMITTED = 1;
int ISOLATION_READ_COMMITTED = 2; 
int ISOLATION_REPEATABLE_READ = 4;
int ISOLATION_SERIALIZABLE = 8;

默认超时

int TIMEOUT_DEFAULT = -1;

然后,有一个获取默认事务定义的方法(用意待考):

static TransactionDefinition withDefaults() {
     return StaticTransactionDefinition.INSTANCE;
 }

DefaultTransactionAttribute

其中比较重要的一个方式是rollbackOn:

public boolean rollbackOn(Throwable ex) {
     return (ex instanceof RuntimeException || ex instanceof Error);
 }

我们先来看看JavaDoc:

The default behavior is as with EJB: rollback on unchecked exception (RuntimeException), assuming an unexpected outcome outside of any business rules. Additionally, we also attempt to rollback on Error which is clearly an unexpected outcome as well. By contrast, a checked exception is considered a business exception and therefore a regular expected outcome of the transactional business method, i.e. a kind of alternative return value which still allows for regular completion of resource operations.
This is largely consistent with TransactionTemplate's default behavior, except that TransactionTemplate also rolls back on undeclared checked exceptions (a corner case). For declarative transactions, we expect checked exceptions to be intentionally declared as business exceptions, leading to a commit by default.

 默认行为与EJB相同:发生运行时异常或发生Error时回滚。而对于check exception一般会被认为是一个业务可以认可或期望的结果,因此是允许交易完成的。这个默认行为与TransactionTemplate的默认行为是保持一致的。

大概的意思是说:默认情况下发生运行时异常或Error的时候事务回滚。而这个默认行为就是通过这个rollbackOn方法来保证的:

public boolean rollbackOn(Throwable ex) {
        return (ex instanceof RuntimeException || ex instanceof Error);
    }

Spring事务控制中的事务定义的最终落地实现就是这个TransactionAttribute,不过他是通过TransactionAttributeSource持有的,后续分析Spring事务启用机制@EnalbeTransactionManagment的时候会看到。

TransactionDefinition的研究就到这里,下一篇文章研究TransactionStatus。

以上就是Spring事务框架之TransactionDefinition源码解析的详细内容,更多关于Spring事务TransactionDefinition的资料请关注脚本之家其它相关文章!

相关文章

最新评论