Spring聲明式交易管理淺述
首先我們先瞭解事務,什麼是事務?
簡單來說就是要麼全部成功,要麼什麼都不做。
為什麼要使用事務?
比如說常用銀行系統的例子,如果沒有用事務,有人在存入錢的時候出了問題,那麼銀行系統資料庫的資料沒有改變,但使用者的錢卻沒了,這樣就會出現很多問題。如果我們把整個存錢的過程看做一個事務,要麼全部成功要麼全部失敗,這樣就可以避免以上存在的問題。
聲明式交易管理:
聲明式交易管理也有兩種常用的方式,一種是基於tx和aop名字空間的xml設定檔,另一種就是基於@Transactional註解。顯然基於註解的方式更簡單易用,更清爽。
先使用配tx和aop名字空間的xml設定檔
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
//以add、del、mod、開頭的方法使用事務
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="mod*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
//news.dao.*.*(..))意思是我們項目中news包下面的dao包下面所有類以及所有方法都可以引入交易管理。
<aop:pointcut id="interceptorPointCuts"
expression="execution(*
news.dao.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
</aop:config>
這樣我們配置完了以後只需要注意使用事務方法命名,當然如果沒有注意命名空間又要使用事務,我們也可以新添加一個<tx:method>
使用@Transactional註解實現交易管理
@Override
//該方法使用事務
@Transactional(readOnly=true)
public List showAllNews() {
List<News> allNewList = nd.showAllNews();
return allNewList;
}
使用@Transactional註解,首先設定檔中無需配置tx:advice和aop:config,我們只需要在需要用事務的方法前面加@Transactional註解就可以了。
總結:兩種方法各有優點,使用設定檔更好的解耦,換一個項目依然可以用,只需要該<tx:method name="del*">中的name的命名空間,和<aop:pointcut id="interceptorPointCuts" expression="execution(*news.dao.*.*(..))" />中execution()括弧中的的命名。而使用@Transactional註解則更加簡單直接,可讀性更高。這裡我建議大項目使用設定檔,小項目使用@Transactional註解。
Spring中如何配置Hibernate事務
Struts2整合Spring方法及原理
基於 Spring 設計並實現 RESTful Web Services
Spring-3.2.4 + Quartz-2.2.0整合執行個體
使用 Spring 進行單元測試
運用Spring註解實現Netty伺服器端UDP應用程式
Spring 3.x 公司專屬應用程式開發實戰 PDF完整高清掃描版+原始碼
Spring 的詳細介紹:請點這裡
Spring 的:請點這裡
本文永久更新連結地址:https://www.bkjia.com/Linux/2018-02/151006.htm