轉自 http://www.javaeye.com/topic/78674
Spring聲明式事務讓我們從複雜的事務處理中得到解脫。使得我們再也無需要去處理獲得連接、關閉連接、事務提交和回滾等這些操作。再也無需要我們在與事務相關的方法中處理大量的try…catch…finally代碼。
我們在使用Spring聲明式事務時,有一個非常重要的概念就是事務屬性。事務屬性通常由事務的傳播行爲,事務的隔離級別,事務的超時值和事務只讀標誌組成。我們在進行事務劃分時,需要進行事務定義,也就是配置事務的屬性。
Spring在TransactionDefinition
接口中定義這些屬性,以供PlatfromTransactionManager使用, PlatfromTransactionManager是spring事務管理的核心接口。
- TransactionDefinition
- public interface TransactionDefinition {
- int getPropagationBehavior();
- int getIsolationLevel();
- int getTimeout();
- boolean isReadOnly();
- }
TransactionDefinition
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
int getTimeout();
boolean isReadOnly();
}
getTimeout()方法,它返回事務必須在多少秒內完成。
isReadOnly(),事務是否只讀,事務管理器能夠根據這個返回值進行優化,確保事務是隻讀的。
getIsolationLevel()方法返回事務的隔離級別,事務管理器根據它來控制另外一個事務可以看到本事務內的哪些數據。
髒讀(dirty read
):當一個事務讀取另一個事務尚未提交的修改時,產生髒讀。
非重複讀(nonrepeatable read
):同一查詢在同一事務中多次進行,由於其他提交事務所做的修改或刪除,每次返回不同的結果集,此時發生非重複讀。(A
transaction rereads data it has previously read and finds that another
committed transaction has modified or deleted the data. )
幻像讀(phantom read
):同一查詢在同一事務中多次進行,由於其他提交事務所做的插入操作,每次返回不同的結果集,此時發生幻像讀。(A
transaction reexecutes a query returning a set of rows that satisfies a
search condition and finds that another committed transaction has
inserted additional rows that satisfy the condition. )
在TransactionDefinition接口中定義了五個不同的事務隔離級別
ISOLATION_DEFAULT
這是一個PlatfromTransactionManager默認的隔離級別,使用數據庫默認的事務隔離級別
.另外四個與JDBC的隔離級別相對應
ISOLATION_READ_UNCOMMITTED
這是事務最低的隔離級別,它充許另外一個事務可以看到這個事務未提交的數據
。這種隔離級別會產生髒讀,不可重複讀和幻像讀。
例如:
Mary的原工資爲1000,財務人員將Mary的工資改爲了8000,但未提交事務
- Connection con1 = getConnection();
- con.setAutoCommit(false );
- update employee set salary = 8000 where empId ="Mary" ;
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();
Connection con2 = getConnection();
select salary from employee where empId ="Mary";
con2.commit();
Mary發現自己的工資變爲了8000,歡天喜地!
而財務發現操作有誤,而回滾了事務,Mary的工資又變爲了1000
- //con1
- con1.rollback();
//con1
con1.rollback();
像這樣,Mary記取的工資數8000是一個髒數據。
ISOLATION_READ_COMMITTED
保證一個事務修改的數據提交後才能被另外一個事務讀取。另外一個事務不能讀取該事務未提交的數據
。這種事務隔離級別可以避免髒讀出現,但是可能會出現不可重複讀和幻像讀。
ISOLATION_REPEATABLE_READ
這種事務隔離級別可以防止髒讀,不可重複讀。但是可能出現幻像讀。它除了保證一個事務不能讀取另一個事務未提交的數據外,還保證了避免下面的情況產生(不可重複讀)。
在事務1中,Mary 讀取了自己的工資爲1000,操作並沒有完成
- con1 = getConnection();
- select salary from employee empId ="Mary" ;
con1 = getConnection();
select salary from employee empId ="Mary";
在事務2中,這時財務人員修改了Mary的工資爲2000,並提交了事務.
- con2 = getConnection();
- update employee set salary = 2000 ;
- con2.commit();
con2 = getConnection();
update employee set salary = 2000;
con2.commit();
在事務1中,Mary 再次讀取自己的工資時,工資變爲了2000
- //con1
- select salary from employee empId ="Mary" ;
//con1
select salary from employee empId ="Mary";
在一個事務中前後兩次讀取的結果並不致,導致了不可重複讀。
使用ISOLATION_REPEATABLE_READ可以避免這種情況發生。
ISOLATION_SERIALIZABLE
這是花費最高代價但是最可靠的事務隔離級別。事務被處理爲順序執行。除了防止髒讀,不可重複讀外,還避免了幻像讀。
目前工資爲1000的員工有10人。
事務1,讀取所有工資爲1000的員工。
- con1 = getConnection();
- Select * from employee where salary =1000 ;
con1 = getConnection();
Select * from employee where salary =1000;
共讀取10條記錄
這時另一個事務向employee表插入了一條員工記錄,工資也爲1000
- con2 = getConnection();
- Insert into employee(empId,salary) values("Lili" ,1000 );
- con2.commit();
con2 = getConnection();
Insert into employee(empId,salary) values("Lili",1000);
con2.commit();
事務1再次讀取所有工資爲1000的員工
- //con1
- select * from employee where salary =1000 ;
//con1
select * from employee where salary =1000;
共讀取到了11條記錄,這就產生了幻像讀。
ISOLATION_SERIALIZABLE能避免這樣的情況發生。但是這樣也耗費了最大的資源。
getPropagationBehavior()
返回事務的傳播行爲,由是否有一個活動的事務來決定一個事務調用。
在TransactionDefinition接口中定義了七個事務傳播行爲
。
PROPAGATION_REQUIRED
如果存在一個事務,則支持當前事務。如果沒有事務則開啓一個新的事務。
- //事務屬性 PROPAGATION_REQUIRED
- methodA{
- ……
- methodB();
- ……
- }
- //事務屬性 PROPAGATION_REQUIRED
- methodB{
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA{
……
methodB();
……
}
//事務屬性 PROPAGATION_REQUIRED
methodB{
……
}
使用spring聲明式事務,spring使用AOP來支持聲明式事務,會根據事務屬性,自動在方法調用之前決定是否開啓一個事務,並在方法執行之後決定事務提交或回滾事務。
單獨調用methodB方法
- main{
- metodB();
- }
main{
metodB();
}
相當於
- Main{
- Connection con=null ;
- rry{
- con = getConnection();
- con.setAutoCommit(false );
- //方法調用
- methodB();
- //提交事務
- con.commit();
- }
- Catch(RuntimeException ex){
- //回滾事務
- con.rollback();
- }
- finally {
- //釋放資源
- closeCon();
- }
- }
Main{
Connection con=null;
rry{
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();
- }
- }
main{
Connection con = null;
try{
con = getConnection();
methodA();
con.commit();
}
cathc(RuntimeException ex){
con.rollback();
}
finally{
closeCon();
}
}
調用MethodA時,環境中沒有事務,所以開啓一個新的事務.
當在MethodA中調用MethodB時,環境中已經有了一個事務,所以methodB就加入當前事務。
PROPAGATION_SUPPORTS
如果存在一個事務,支持當前事務。如果沒有事務,則非事務的執行
。但是對於事務同步的事務管理器,PROPAGATION_SUPPORTS與不使用事務有少許不同。
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- methodB();
- }
- //事務屬性 PROPAGATION_SUPPORTS
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
methodB();
}
//事務屬性 PROPAGATION_SUPPORTS
methodB(){
……
}
單純的調用methodB時,methodB方法是非事務的執行的。
當調用methdA時,methodB則加入了methodA的事務中,事務地執行。
PROPAGATION_MANDATORY 如果已經存在一個事務,支持當前事務。如果沒有一個活動的事務,則拋出異常。
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- methodB();
- }
- //事務屬性 PROPAGATION_MANDATORY
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
methodB();
}
//事務屬性 PROPAGATION_MANDATORY
methodB(){
……
}
當單獨調用methodB時,因爲當前沒有一個活動的事務,則會拋出異常
throw new IllegalTransactionStateException("Transaction propagation 'mandatory' but no existing transaction found");
當調用methodA時,methodB則加入到methodA的事務中,事務地執行。
PROPAGATION_REQUIRES_NEW
總是開啓一個新的事務。如果一個事務已經存在,則將這個存在的事務掛起。
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- doSomeThingA();
- methodB();
- doSomeThingB();
- }
- //事務屬性 PROPAGATION_REQUIRES_NEW
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
methodB();
doSomeThingB();
}
//事務屬性 PROPAGATION_REQUIRES_NEW
methodB(){
……
}
當單獨調用methodB時,相當於把methodb聲明爲REQUIRED。開啓一個新的事務,事務地執行。
當調用methodA時
- main(){
- 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 {
- //釋放資源
- }
- }
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作爲事務管理器。
PROPAGATION_NOT_SUPPORTED
總是非事務地執行,並掛起任何存在的事務。
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- doSomeThingA();
- methodB();
- doSomeThingB();
- }
- //事務屬性 PROPAGATION_NOT_SUPPORTED
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
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 {
- //釋放資源
- }
- }
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作爲事務管理器。
PROPAGATION_NEVER
總是非事務地執行,如果存在一個活動事務,則拋出異常
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- doSomeThingA();
- methodB();
- doSomeThingB();
- }
- //事務屬性 PROPAGATION_NEVER
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
methodB();
doSomeThingB();
}
//事務屬性 PROPAGATION_NEVER
methodB(){
……
}
單獨調用methodB,則非事務的執行。
調用methodA則會拋出異常
throw new IllegalTransactionStateException(
"Transaction propagation 'never' but existing transaction found");
PROPAGATION_NESTED
如果一個活動的事務存在,則運行在一個嵌套的事務中. 如果沒有活動事務, 則按TransactionDefinition.PROPAGATION_REQUIRED 屬性執行
這是一個嵌套事務,使用JDBC 3.0驅動時,僅僅支持DataSourceTransactionManager作爲事務管理器。需要JDBC 驅動的java.sql.Savepoint類。有一些JTA的事務管理器實現可能也提供了同樣的功能。
使用PROPAGATION_NESTED,還需要把PlatformTransactionManager的nestedTransactionAllowed屬性設爲true;
而nestedTransactionAllowed屬性值默認爲false;
- //事務屬性 PROPAGATION_REQUIRED
- methodA(){
- doSomeThingA();
- methodB();
- doSomeThingB();
- }
- //事務屬性 PROPAGATION_NESTED
- methodB(){
- ……
- }
//事務屬性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
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 {
- //釋放資源
- }
- }
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應該是我們首先的事務傳播行爲。它能夠滿足我們大多數的事務需求。