spring事务原理1-事务的抽象

概要

spring事务包含3个最主要的接口PlatformTransactionManager,TransactionStatus,TransactionDefinition 。其中PlatformTransactionManager负责管理事务的边界,
TransactionStatus负责描述事务的状态,TransactionDefinition定义事务相关属性,例如隔离级别,传播行为等。

PlatformTransactionManager

PlatformTransactionManager 的整个抽象体系基于Strategy 模式,由PlatformTransactionManager 对事务界定进行统一抽象,而具体的界定策略的实现则交由具体的实现类。

public interface PlatformTransactionManager {

  TransactionStatus getTransaction(TransactionDefinition definition)
    throws TransactionException;

  void commit(TransactionStatus status) throws TransactionException;

  void rollback(TransactionStatus status) throws TransactionException;
}

TransactionDefinition

TransactionDefinition定义了事务的相关属性:隔离级别,传播性,超时,只读状态。

  • Isolation: The degree to which this transaction is isolated from the work of other transactions. For example, can this transaction see uncommitted writes from other transactions?

  • Propagation: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see Section 10.5.7, “Transaction propagation”.

  • Timeout: How long this transaction runs before timing out and being rolled back automatically by the underlying transaction infrastructure.

  • Read-only status: A read-only transaction can be used when your code reads but does not modify data. Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate.

TransactionStatus

org.springframework.transaction.TransactionStatus 接口定义表示整个事务处理过程中的事务状态,更多时候,我们将在编程式事务中使用该接口。

public interface TransactionStatus extends SavepointManager {

    boolean isNewTransaction();

    boolean hasSavepoint();

    void setRollbackOnly();

    boolean isRollbackOnly();

    void flush();

    boolean isCompleted();

}

在事务处理过程中,我们可以使用TransactionStatus 进行如下工作。

  • 使用TransactionStatus 提供的相应方法查询事务状态。
  • 通过setRollbackOnly() 方法标记当前事务以使其回滚。
  • 如果相应的PlatformTransactionManager支持Savepoint,可以通过TransactionStatus 在当前事务中创建内部嵌套事务。