Spring中@Transactional用法深度分析之一

引言: 在Spring中@Transactional提供一種控制事務管理的快捷手段,但是很多人都只是@Transactional簡單使用,並未深入瞭解,其各個配置項的使用方法,本文將深入講解各個配置項的使用。

1.  @Transactional的定義

    Spring中的@Transactional基於動態代理的機制,提供了一種透明的事務管理機制,方便快捷解決在開發中碰到的問題。在現實中,實際的問題往往比我們預期的要複雜很多,這就要求對@Transactional有深入的瞭解,以來應對複雜問題。

   首先我們來看看@Transactional的代碼定義:

@Target({ElementType.METHOD, ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Inherited

@Documented

public @interface Transactional {


/**

* A qualifier value for the specified transaction.

* <p>May be used to determine the target transaction manager,

* matching the qualifier value (or the bean name) of a specific

* {@link org.springframework.transaction.PlatformTransactionManager}

* bean definition.

*/

String value() default "";


/**

* The transaction propagation type.

* Defaults to {@link Propagation#REQUIRED}.

* @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()

*/

Propagation propagation() default Propagation.REQUIRED;


/**

* The transaction isolation level.

* Defaults to {@link Isolation#DEFAULT}.

* @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel()

*/

Isolation isolation() default Isolation.DEFAULT;


/**

* The timeout for this transaction.

* Defaults to the default timeout of the underlying transaction system.

* @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()

*/

int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;


/**

* {@code true} if the transaction is read-only.

* Defaults to {@code false}.

* <p>This just serves as a hint for the actual transaction subsystem;

* it will <i>not necessarily</i> cause failure of write access attempts.

* A transaction manager which cannot interpret the read-only hint will

* <i>not</i> throw an exception when asked for a read-only transaction.

* @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()

*/

boolean readOnly() default false;


/**

* Defines zero (0) or more exception {@link Class classes}, which must be a

* subclass of {@link Throwable}, indicating which exception types must cause

* a transaction rollback.

* <p>This is the preferred way to construct a rollback rule, matching the

* exception class and subclasses.

* <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}

*/

Class<? extends Throwable>[] rollbackFor() default {};


/**

* Defines zero (0) or more exception names (for exceptions which must be a

* subclass of {@link Throwable}), indicating which exception types must cause

* a transaction rollback.

* <p>This can be a substring, with no wildcard support at present.

* A value of "ServletException" would match

* {@link javax.servlet.ServletException} and subclasses, for example.

* <p><b>NB: </b>Consider carefully how specific the pattern is, and whether

* to include package information (which isn't mandatory). For example,

* "Exception" will match nearly anything, and will probably hide other rules.

* "java.lang.Exception" would be correct if "Exception" was meant to define

* a rule for all checked exceptions. With more unusual {@link Exception}

* names such as "BaseBusinessException" there is no need to use a FQN.

* <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)}

*/

String[] rollbackForClassName() default {};


/**

* Defines zero (0) or more exception {@link Class Classes}, which must be a

* subclass of {@link Throwable}, indicating which exception types must <b>not</b>

* cause a transaction rollback.

* <p>This is the preferred way to construct a rollback rule, matching the

* exception class and subclasses.

* <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)}

*/

Class<? extends Throwable>[] noRollbackFor() default {};


/**

* Defines zero (0) or more exception names (for exceptions which must be a

* subclass of {@link Throwable}) indicating which exception types must <b>not</b>

* cause a transaction rollback.

* <p>See the description of {@link #rollbackForClassName()} for more info on how

* the specified names are treated.

* <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)}

*/

String[] noRollbackForClassName() default {};


}

  基於源代碼,我們可以發現在@Transactional,原來有這麼多的屬性可以進行配置,從而達到複雜應用控制的目的。具體各個屬性的用法和作用,將在本文的後面逐一進行講解和說明。

 

2.  使用@Transactional的Spring配置

     爲了使用基於@Transactional的事務管理,需要在Spring中進行如下的配置:

<beans:bean id="transactionManager"

class="org.springframework.orm.jpa.JpaTransactionManager">

<beans:property name="dataSource" ref="dataSource" />

<beans:property name="entityManagerFactory" ref="entityManagerFactory" />

</beans:bean>


<!-- 聲明使用註解式事務 -->

<tx:annotation-driven transaction-manager="transactionManager" />

    dataSource是在Spring配置文件中定義的數據源的對象實例,EntityManagerFactory是基於JPA使用的實體類管理器:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean。這些都是用來配置與數據庫的連接信息,本質上,@Transactional使用了JDBC的事務來進行事務控制的。

    <annotation-driven>標籤的聲明,則是在Spring內部啓用@Transactional來進行事務管理,類似開關之類的聲明。

3.  @Transactional之value

    value這裏主要用來指定不同的事務管理器;主要用來滿足在同一個系統中,存在不同的事務管理器。比如在Spring中,聲明瞭兩種事務管理器txManager1, txManager2.

然後,用戶可以根據這個參數來根據需要指定特定的txManager.

   那有同學會問什麼情況下會存在多個事務管理器的情況呢? 比如在一個系統中,需要訪問多個數據源或者多個數據庫,則必然會配置多個事務管理器的。

4.   @Transactional之propagation

      Propagation支持7種不同的傳播機制:

  •  REQUIRED

               業務方法需要在一個事務中運行,如果方法運行時,已處在一個事務中,那麼就加入該事務,否則自己創建一個新的事務.這是spring默認的傳播行爲.。 

  •  SUPPORTS: 

               如果業務方法在某個事務範圍內被調用,則方法成爲該事務的一部分,如果業務方法在事務範圍外被調用,則方法在沒有事務的環境下執行。

  •  MANDATORY:

               只能在一個已存在事務中執行,業務方法不能發起自己的事務,如果業務方法在沒有事務的環境下調用,就拋異常

  •  REQUIRES_NEW

             業務方法總是會爲自己發起一個新的事務,如果方法已運行在一個事務中,則原有事務被掛起,新的事務被創建,直到方法結束,新事務才結束,原先的事務纔會恢復執行.

  •  NOT_SUPPORTED

           聲明方法需要事務,如果方法沒有關聯到一個事務,容器不會爲它開啓事務.如果方法在一個事務中被調用,該事務會被掛起,在方法調用結束後,原先的事務便會恢復執行.

  • NEVER:

              聲明方法絕對不能在事務範圍內執行,如果方法在某個事務範圍內執行,容器就拋異常.只有沒關聯到事務,才正常執行.

  •  NESTED:

          如果一個活動的事務存在,則運行在一個嵌套的事務中.如果沒有活動的事務,則按REQUIRED屬性執行.它使用了一個單獨的事務, 這個事務擁有多個可以回滾的保證點.內部事務回滾不會對外部事務造成影響, 它只對DataSourceTransactionManager 事務管理器起效.

     其實大家最感到困惑的是REQUIRED_NEW和NESTED兩種不同的傳播機制,功能類似,都涉及到了事務嵌套的問題,那兩者有何區別呢?該如何正確使用這兩種模式呢?

        以下是摘自Spring的文檔:

          PROPAGATION_REQUIRES_NEW : uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status.

         內部的事務獨立運行,在各自的作用域中,可以獨立的回滾或者提交;而外部的事務將不受內部事務的回滾狀態影響。 

        ROPAGATION_NESTED : uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. This setting is typically mapped onto JDBC savepoints, so will only work with JDBC resource transactions.

       NESTED的事務,基於單一的事務來管理,提供了多個保存點。這種多個保存點的機制允許內部事務的變更觸發外部事務的回滾。而外部事務在回滾之後,仍能繼續進行事務處理,即使部分操作已經被回滾。 由於這個設置基於JDBC的保存點,所以只能工作在JDBC的機制之上。

       由此可知, 兩者都是事務嵌套,不同之處在於,內外事務之間是否存在彼此之間的影響;NESTED之間會受到影響,而產生部分回滾,而REQUIRED_NEW則是獨立的。

 

轉自 https://blog.csdn.net/blueheart20/article/details/44654007

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章