1. 程式人生 > >Spring 事務的配置和使用詳解(包括手動對事務的控制部分)

Spring 事務的配置和使用詳解(包括手動對事務的控制部分)

最近專案中用到了spring的註解類的事務管理,所以特地學習和記錄一下spring的配置和使用。專案中使用的是springMVC + mybatis + mysql。spring的版本是4.3.0.RELEASE

1. spring 註解事務的配置

Spring配置檔案中關於事務配置總是由三個組成部分,分別是DataSource、TransactionManager和代理機制這三部分,無論哪種配置方式,一般變化的只是代理機制這部分。
這裡寫圖片描述
(1)spring+mybatis 事務配置
xml配置檔案的名稱空間的引用:如下斜體所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" *xmlns:tx="http://www.springframework.org/schema/tx"* xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd *http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd* http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
>
<!-- 註冊事務管理類 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 開啟事務行為 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

(2)Spring+hibernate

<!-- 事務管理器配置,單資料來源事務 -->  
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
    <property name="sessionFactory" ref="sessionFactory" />  
</bean>  

<!-- 使用annotation定義事務 -->  
<tx:annotation-driven  transaction-manager="transactionManager"   proxy-target-class="true" />  

注:根據使用不同的orm框架,事務管理器就不同。使用mybatis使用:

org.springframework.jdbc.datasource.DataSourceTransactionManager

而使用hibernate,則事務管理器類為:

org.springframework.orm.hibernate3.HibernateTransactionManager

事務的傳播性、隔離性級別一般設定在service層。

2.spring事務的傳播性、隔離性。

@Transactional
(1)這裡說明一下,有的把這個註解放在類名稱上面了,這樣你配置的這個@Transactional 對這個類中的所有public方法都起作用.
(2)@Transactional 方法方法名上,只對這個方法有作用,同樣必須是public的方法

我們在使用Spring宣告式事務時,有一個非常重要的概念就是事務的屬性。事務屬性通常由事務的傳播行為、事務的隔離級別、事務的超時值和事務的只讀標識組成。我們在進行事務劃分時,需要進行事務定義,也就是配置事務的屬性。

Spring在TransactionDefinition介面中定義這些屬性,以供PlatfromTransactionManager使用, PlatfromTransactionManager是spring事務管理的核心介面。

TransactionDefinition  
public interface TransactionDefinition {  
    int getPropagationBehavior();  
    int getIsolationLevel();  
    int getTimeout();  
    boolean isReadOnly();  
}  

getTimeout()方法,它返回事務必須在多少秒內完成。
isReadOnly(),事務是否只讀,事務管理器能夠根據這個返回值進行優化,確保事務是隻讀的。
getIsolationLevel()方法返回事務的隔離級別,事務管理器根據它來控制另外一個事務可以看到本事務內的哪些資料。

一。事務的隔離級別

在TransactionDefinition介面中定義了五個不同的事務隔離級別 :
(a) ISOLATION_DEFAULT:(PlatfromTransactionManager的)預設的隔離級別。使用資料庫預設的事務隔離級別.另外四個與JDBC的隔離級別相對應 。
(b)ISOLATION_READ_UNCOMMITTED:這是事務最低的隔離級別,它充許別外一個事務可以看到這個事務未提交的資料。這種隔離級別會產生髒讀,不可重複讀和幻像讀。
例如:
Mary的原工資為1000,財務人員將Mary的工資改為了8000,但未提交事務

Connection con1 = getConnection();  
con.setAutoCommit(false);  
update employee set salary = 8000 where empId ="Mary"; 

與此同時,Mary正在讀取自己的工資 。

Connection con2 = getConnection();  
select  salary from employee where empId ="Mary";  
con2.commit();

Mary發現自己的工資變為了8000,歡天喜地!
而財務發現操作有誤,而回滾了事務,Mary的工資又變為了1000 。

//con1  
  con1.rollback(); 

像這樣,Mary記取的工資數8000是一個髒資料。

(c)ISOLATION_READ_COMMITTED: 保證一個事務修改的資料提交後才能被另外一個事務讀取。另外一個事務不能讀取該事務未提交的資料。這種事務隔離級別可以避免髒讀出現,但是可能會出現不可重複讀和幻像讀。

(d)ISOLATION_REPEATABLE_READ : 這種事務隔離級別可以防止髒讀,不可重複讀。但是可能出現幻像讀。它除了保證一個事務不能讀取另一個事務未提交的資料外,還保證了避免下面的情況產生(不可重複讀)。

例如:
在事務1中,Mary 讀取了自己的工資為1000,操作並沒有完成 :

con1 = getConnection();  
select salary from employee empId ="Mary";  

在事務2中,這時財務人員修改了Mary的工資為2000,並提交了事務.

con2 = getConnection();  
update employee set salary = 2000;  
con2.commit();  

在事務1中,Mary 再次讀取自己的工資時,工資變為了2000

//con1  
select salary from employee empId ="Mary";  

在一個事務中前後兩次讀取的結果並不致,導致了不可重複讀。
使用ISOLATION_REPEATABLE_READ可以避免這種情況發生。

(e)ISOLATION_SERIALIZABLE 這是花費最高代價但是最可靠的事務隔離級別。事務被處理為順序執行。除了防止髒讀,不可重複讀外,還避免了幻像讀。

目前工資為1000的員工有10人。
事務1,讀取所有工資為1000的員工。

con1 = getConnection();  
Select * from employee where salary =1000; 

共讀取10條記錄

這時另一個事務向employee表插入了一條員工記錄,工資也為1000

con2 = getConnection();  
Insert into employee(empId,salary) values("Lili",1000);  
con2.commit();  

事務1再次讀取所有工資為1000的員工

select * from employee where salary =1000;  

共讀取到了11條記錄,這就產生了幻像讀。
ISOLATION_SERIALIZABLE能避免這樣的情況發生。但是這樣也耗費了最大的資源。

getPropagationBehavior()返回事務的傳播行為,由是否有一個活動的事務來決定一個事務呼叫。

二。事務的傳播性

在TransactionDefinition介面中定義了七個事務傳播行為。

假如我寫了兩個service類。名字分別為ServiceA和ServiceB。如下:

@Service("ServiceA")
public class ServiceA {

    @Resource(name="ServiceB")
    private ServiceB serviceB;

    @Transactional(propagation=Propagation.REQUIRED)
    public methodA(){
       //doSomething
       serviceB.methodB(); 
       //doSomething
    }
}
@Service("ServiceB")
public class ServiceB {

    @Transactional(propagation=Propagation.REQUIRED)
    public methodB(){
       //doSomething
    }
}

使用spring宣告式事務,spring使用AOP來支援宣告式事務,會根據事務屬性,自動在方法呼叫之前決定是否開啟一個事務,並在方法執行之後決定事務提交或回滾事務。

(a)PROPAGATION_REQUIRED:如果存在一個事務,則支援當前事務。如果沒有事務則開啟一個新的事務。
如果單獨呼叫serviceB.methodB方法:

main {
   serviceB.methodB();
}

相當於:

Main{  
  Connection con=null;  
  try{  
      con = getConnection();  
      con.setAutoCommit(false);  
      //方法呼叫  
      methodB();  
      //提交事務  
      con.commit();  
 }Catch(RuntimeException ex){  
    //回滾事務  
    con.rollback();    
 }finally{  
    //釋放資源  
    closeCon();  
 }  
}  

Spring保證在methodB方法中所有的呼叫都獲得到一個相同的連線。在呼叫methodB時,沒有一個存在的事務,所以獲得一個新的連線,開啟了一個新的事務。

如果單獨呼叫MethodA時,在MethodA內又會呼叫MethodB.
執行效果相當於:

main{  
   Connection con = null;  
   try{  
      con = getConnection();  
      methodA();  
      con.commit();  
   }cathc(RuntimeException ex){  
      con.rollback();  
   }finally{  
      closeCon();  
   }   
}  

呼叫MethodA時,環境中沒有事務,所以開啟一個新的事務.
當在MethodA中呼叫MethodB時,環境中已經有了一個事務,所以methodB就加入當前事務。

(b)PROPAGATION_SUPPORTS :如果存在一個事務,支援當前事務。如果沒有事務,則非事務的執行。但是對於事務同步的事務管理器,PROPAGATION_SUPPORTS與不使用事務有少許不同。

//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
  serviceB.methodB();  
}  

//事務屬性 PROPAGATION_SUPPORTS   
methodB(){  
  ……  
}  

單純的呼叫methodB時,methodB方法是非事務的執行的。
當呼叫methdA時,methodB則加入了methodA的事務中,事務地執行。

(c)PROPAGATION_MANDATORY :如果已經存在一個事務,支援當前事務。如果沒有一個活動的事務,則丟擲異常。

//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
  serviceB.methodB();  
}  

//事務屬性 PROPAGATION_MANDATORY   
methodB(){  
  ……  
}  

當單獨呼叫methodB時,因為當前沒有一個活動的事務,則會丟擲異常
throw new IllegalTransactionStateException(“Transaction propagation ‘mandatory’ but no existing transaction found”);

當呼叫methodA時,methodB則加入到methodA的事務中,事務地執行。

(d)PROPAGATION_REQUIRES_NEW :總是開啟一個新的事務。如果一個事務已經存在,則將這個存在的事務掛起。

//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
   doSomeThingA();  
   serviceB.methodB();  
   doSomeThingB();  
}  

//事務屬性 PROPAGATION_REQUIRES_NEW   
methodB(){  
  ……  
}  

當單獨呼叫methodB時,相當於把methodb宣告為REQUIRED。開啟一個新的事務,事務地執行。

當呼叫methodA時:

main(){  
  methodA();  
}  

情況就大不一樣了,相當於下面的效果。

main(){  
 TransactionManager tm = null;  
 try{  
  //獲得一個JTA事務管理器  
   tm = getTransactionManager();  
   tm.begin();//開啟一個新的事務  
   Transaction ts1 = tm.getTransaction();  
   doSomeThing();  
   tm.suspend();//掛起當前事務  
   try{  
     tm.begin();//重新開啟第二個事務  
     Transaction ts2 = tm.getTransaction();  
     methodB();  
     ts2.commit();//提交第二個事務  

   }Catch(RunTimeException ex){  
     ts2.rollback();//回滾第二個事務  
   }finally{  
    //釋放資源  
   }  
   //methodB執行完後,復恢第一個事務  
   tm.resume(ts1);  
   doSomeThingB();  
   ts1.commit();//提交第一個事務  
 }catch(RunTimeException ex){  
  ts1.rollback();//回滾第一個事務  
 }finally{  
  //釋放資源  
 }  
}  

在這裡,我把ts1稱為外層事務,ts2稱為內層事務。從上面的程式碼可以看出,ts2與ts1是兩個獨立的事務,互不相干。Ts2是否成功並不依賴於ts1。如果methodA方法在呼叫methodB方法後的doSomeThingB方法失敗了,而methodB方法所做的結果依然被提交。而除了methodB之外的其它程式碼導致的結果卻被回滾了。
使用PROPAGATION_REQUIRES_NEW,需要使用JtaTransactionManager作為事務管理器。

(e)PROPAGATION_NOT_SUPPORTED: 總是非事務地執行,並掛起任何存在的事務。

//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
  doSomeThingA();  
  serviceB.methodB();  
  doSomeThingB();  
}  

//事務屬性 PROPAGATION_NOT_SUPPORTED   
methodB(){  
  ……  
}  

當單獨呼叫methodB時,不啟用任何事務機制,非事務地執行。

當呼叫methodA時,相當於下面的效果

main(){  
 TransactionManager tm = null;  
 try{  
  //獲得一個JTA事務管理器  
   tm = getTransactionManager();  
   tm.begin();//開啟一個新的事務  
   Transaction ts1 = tm.getTransaction();  
   doSomeThing();  
   tm.suspend();//掛起當前事務  
   methodB();  
   //methodB執行完後,復恢第一個事務  
   tm.resume(ts1);  
   doSomeThingB();  
   ts1.commit();//提交第一個事務  
 }catch(RunTimeException ex){  
   ts1.rollback();//回滾第一個事務  
 }finally{  
  //釋放資源  
 }  
}  

使用PROPAGATION_NOT_SUPPORTED,也需要使用JtaTransactionManager作為事務管理器。

(f)PROPAGATION_NEVER :總是非事務地執行,如果存在一個活動事務,則丟擲異常:

//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
  doSomeThingA();  
  seviceB.methodB();  
  doSomeThingB();  
}  

//事務屬性 PROPAGATION_NEVER   
methodB(){  
  ……  
}  

單獨呼叫methodB,則非事務的執行。
呼叫methodA則會丟擲異常
throw new IllegalTransactionStateException(
“Transaction propagation ‘never’ but existing transaction found”);

(g)PROPAGATION_NESTED:如果一個活動的事務存在,則執行在一個巢狀的事務中. 如果沒有活動事務, 則按TransactionDefinition.PROPAGATION_REQUIRED 屬性執行

這是一個巢狀事務,使用JDBC 3.0驅動時,僅僅支援DataSourceTransactionManager作為事務管理器。需要JDBC 驅動的java.sql.Savepoint類。有一些JTA的事務管理器實現可能也提供了同樣的功能。

使用PROPAGATION_NESTED,還需要把PlatformTransactionManager的nestedTransactionAllowed屬性設為true;
而nestedTransactionAllowed屬性值預設為false;
例如如下:

<bean id="system.platformTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
        <property name="sessionFactory" ref="system.sessionFactory"/>  
        <property name="nestedTransactionAllowed" value="true"/>  
    </bean>
//事務屬性 PROPAGATION_REQUIRED   
methodA(){  
  doSomeThingA();  
  serviceB.methodB();  
  doSomeThingB();  
}  

//事務屬性 PROPAGATION_NESTED  
methodB(){  
  ……  
}  

如果單獨呼叫methodB方法,則按REQUIRED屬性執行。

如果呼叫methodA方法,相當於下面的效果

main(){  
Connection con = null;  
Savepoint savepoint = null;  
try{  
  con = getConnection();  
  con.setAutoCommit(false);  
  doSomeThingA(); 
  //創造一個事務的儲存點 
  savepoint = con2.setSavepoint();  
  try  
      methodB();  
  }catch(RuntimeException ex){  
     con.rollback(savepoint);  
  }  
  finally{  
    //釋放資源  
  }  

  doSomeThingB();  
  con.commit();  
}  
catch(RuntimeException ex){  
  con.rollback();  
}  
finally{  
  //釋放資源  
}  
}  

當methodB方法呼叫之前,呼叫setSavepoint方法,儲存當前的狀態到savepoint。如果methodB方法呼叫失敗,則恢復到之前儲存的狀態。但是需要注意的是,這時的事務並沒有進行提交,如果後續的程式碼(doSomeThingB()方法)呼叫失敗,則回滾包括methodB方法的所有操作。

巢狀事務一個非常重要的概念就是內層事務依賴於外層事務。外層事務失敗時,會回滾內層事務所做的動作。而內層事務操作失敗並不會引起外層事務的回滾。

PROPAGATION_NESTED 與PROPAGATION_REQUIRES_NEW的區別:它們非常類似,都像一個巢狀事務,如果不存在一個活動的事務,都會開啟一個新的事務。使用PROPAGATION_REQUIRES_NEW時,內層事務與外層事務就像兩個獨立的事務一樣,一旦內層事務進行了提交後,外層事務不能對其進行回滾。兩個事務互不影響。兩個事務不是一個真正的巢狀事務。同時它需要JTA事務管理器的支援。
使用PROPAGATION_NESTED時,外層事務的回滾可以引起內層事務的回滾。而內層事務的異常並不會導致外層事務的回滾,它是一個真正的巢狀事務。DataSourceTransactionManager使用savepoint支援PROPAGATION_NESTED時,需要JDBC 3.0以上驅動及1.4以上的JDK版本支援。其它的JTA TrasactionManager實現可能有不同的支援方式。

PROPAGATION_REQUIRED應該是我們首先的事務傳播行為。它能夠滿足我們大多數的事務需求。

3。事務的超時性、回滾和只讀

超時:
@Transactional(timeout=30) //預設是30秒

異常回滾:
指定單一異常類:@Transactional(rollbackFor=RuntimeException.class)

指定多個異常類:@Transactional(rollbackFor={RuntimeException.class, Exception.class})
該屬性用於設定需要進行回滾的異常類陣列,當方法中丟擲指定異常陣列中的異常時,則進行事務回滾。

正常的情況下也可以回滾:

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

只讀
@Transactional(readOnly=true)
該屬性用於設定當前事務是否為只讀事務,設定為true表示只讀,false則表示可讀寫,預設值為false。

4。單獨建立事務點手動提交

1、配置檔案 applicationContext.xml:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

2、在需要加事務的方法上加上(有ApplicationContext 的情況下):

//這種情況是有ApplicationContext的情況下,即ctx
DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) ctx
                .getBean("transactionManager");
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔離級別,開啟新事務,這樣會比較安全些。
    TransactionStatus status = transactionManager.getTransaction(def); // 獲得事務狀態
    try {
        //邏輯程式碼,可以寫上你的邏輯處理程式碼
        transactionManager.commit(status);
    } catch (Exception e) {
        transactionManager.rollback(status);
    }

上面是有ApplicationContext 的情況下。

3、ApplicationContext 不存在的情況下:

//可以通過註解實現
 @Autowired
    private DataSourceTransactionManager txManager;
   DefaultTransactionDefinition def = new DefaultTransactionDefinition();
   def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔離級別,開啟新事務
   TransactionStatus status = txManager.getTransaction(def); // 獲得事務狀態
try{
//邏輯程式碼,可以寫上你的邏輯處理程式碼
txManager.commit(status);
}catch(Exception
 e){
txManager.rollback(status);
}