spring提供了幾個(gè)關(guān)于事務(wù)處理的類:?
TransactionDefinition?//事務(wù)屬性定義
TranscationStatus?//代表了當(dāng)前的事務(wù),可以提交,回滾。
PlatformTransactionManager這個(gè)是spring提供的用于管理事務(wù)的基礎(chǔ)接口,其下有一個(gè)實(shí)現(xiàn)的抽象類AbstractPlatformTransactionManager,我們使用的事務(wù)管理類例如DataSourceTransactionManager等都是這個(gè)類的子類。
一般事務(wù)定義步驟:
TransactionDefinition td = new TransactionDefinition();
TransactionStatus ts = transactionManager.getTransaction(td);
try
{ //do sth
? transactionManager.commit(ts);
}
catch(Exception e){transactionManager.rollback(ts);}
?
spring提供的事務(wù)管理可以分為兩類:編程式的和聲明式的。編程式的,比較靈活,但是代碼量大,存在重復(fù)的代碼比較多;聲明式的比編程式的更靈活。
編程式主要使用transactionTemplate。省略了部分的提交,回滾,一系列的事務(wù)對(duì)象定義,需注入事務(wù)管理對(duì)象.
void add()
{
??? transactionTemplate.execute( new TransactionCallback(){
??????? pulic Object doInTransaction(TransactionStatus ts)
?????? { //do sth}
??? }
}
聲明式:
使用TransactionProxyFactoryBean:
<bean id="userManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
??<property name="transactionManager"><ref bean="transactionManager"/></property>
??<property name="target"><ref local="userManagerTarget"/></property>
??<property name="transactionAttributes">
???<props>
????<prop key="insert*">PROPAGATION_REQUIRED</prop>
????<prop key="update*">PROPAGATION_REQUIRED</prop>
????<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
???</props>
??</property>
?</bean>
??<property name="transactionManager"><ref bean="transactionManager"/></property>
??<property name="target"><ref local="userManagerTarget"/></property>
??<property name="transactionAttributes">
???<props>
????<prop key="insert*">PROPAGATION_REQUIRED</prop>
????<prop key="update*">PROPAGATION_REQUIRED</prop>
????<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
???</props>
??</property>
?</bean>
圍繞Poxy的動(dòng)態(tài)代理 能夠自動(dòng)的提交和回滾事務(wù)
org.springframework.transaction.interceptor.TransactionProxyFactoryBean
- PROPAGATION_REQUIRED--支持當(dāng)前事務(wù),如果當(dāng)前沒有事務(wù),就新建一個(gè)事務(wù)。這是最常見的選擇。
- PROPAGATION_SUPPORTS--支持當(dāng)前事務(wù),如果當(dāng)前沒有事務(wù),就以非事務(wù)方式執(zhí)行。
- PROPAGATION_MANDATORY--支持當(dāng)前事務(wù),如果當(dāng)前沒有事務(wù),就拋出異常。
- PROPAGATION_REQUIRES_NEW--新建事務(wù),如果當(dāng)前存在事務(wù),把當(dāng)前事務(wù)掛起。
- PROPAGATION_NOT_SUPPORTED--以非事務(wù)方式執(zhí)行操作,如果當(dāng)前存在事務(wù),就把當(dāng)前事務(wù)掛起。
- PROPAGATION_NEVER--以非事務(wù)方式執(zhí)行,如果當(dāng)前存在事務(wù),則拋出異常。
- PROPAGATION_NESTED--如果當(dāng)前存在事務(wù),則在嵌套事務(wù)內(nèi)執(zhí)行。如果當(dāng)前沒有事務(wù),則進(jìn)行與PROPAGATION_REQUIRED類似的操作。