在使用Spring聲明式事務時,不需要手動的開啟事務和關閉事務,但是對於一些場景則需要開發人員手動的提交事務,比如說一個操作中需要處理大量的數據庫更改,可以將大量的數據庫更改分批的提交,又比如一次事務中一類的操作的失敗並不需要對其他類操作進行事務回滾,就可以將此類的事務先進行提交,這樣就需要手動的獲取Spring管理的Transaction來提交事務。
1、applicationContext.xml配置
1 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 2 <property name="dataSource" ref="dataSource" /> 3 </bean> 4 5 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 6 <tx:attributes> 7 <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception" /> 8 <tx:method name="find*" read-only="true" propagation="SUPPORTS" /> 9 <tx:method name="get*" read-only="true" propagation="SUPPORTS" /> 10 <tx:method name="select*" read-only="true" propagation="SUPPORTS" /> 11 <tx:method name="list*" read-only="true" propagation="SUPPORTS" /> 12 <tx:method name="load*" read-only="true" propagation="SUPPORTS" /> 13 </tx:attributes> 14 </tx:advice> 15 16 <aop:config> 17 <aop:pointcut id="servicePointCut" expression="execution(* com.xxx.xxx.service..*(..))" /> 18 <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointCut" /> 19 </aop:config>
2、手動提交事務
1 @Resource(name="transactionManager") 2 private DataSourceTransactionManager transactionManager; 3 4 DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition(); 5 //開啟新事物 6 transDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW); 7 TransactionStatus transStatus = transactionManager.getTransaction(transDefinition); 8 try { 9 //TODO 10 transactionManager.commit(transStatus); 11 } catch (Exception e) { 12 transactionManager.rollback(transStatus); 13 }