1、聲明式事務配置
* 配置SessionFactory
* 配置交易管理員
* 事務的傳播特性
* 那些類那些方法使用事務
2、編寫商務邏輯方法
* 繼承HibernateDaoSupport類,使用HibernateTemplate來持久化,HibernateTemplate是
Hibernate Session的輕量級封裝
* 預設情況下運行期異常才會復原(包括繼承了RuntimeException子類),普通異常是不會滾的
* 編寫商務邏輯方法時,最好將異常一直向上拋出,在展示層(struts)處理
* 關於事務邊界的設定,通常設定到業務層,不要添加到Dao上
3、瞭解事務的幾種傳播特性
1. PROPAGATION_REQUIRED: 如果存在一個事務,則支援當前事務。如果沒有事務則開啟
2. PROPAGATION_SUPPORTS: 如果存在一個事務,支援當前事務。如果沒有事務,則非事務的執行
3. PROPAGATION_MANDATORY: 如果已經存在一個事務,支援當前事務。如果沒有一個活動的事務,則拋出異常。
4. PROPAGATION_REQUIRES_NEW: 總是開啟一個新的事務。如果一個事務已經存在,則將這個存在的事務掛起。
5. PROPAGATION_NOT_SUPPORTED: 總是非事務地執行,並掛起任何存在的事務。
6. PROPAGATION_NEVER: 總是非事務地執行,如果存在一個活動事務,則拋出異常
7. PROPAGATION_NESTED:如果一個活動的事務存在,則運行在一個嵌套的事務中. 如果沒有活動事務,
則按TransactionDefinition.PROPAGATION_REQUIRED 屬性執行
4、Spring事務的隔離等級
1. ISOLATION_DEFAULT: 這是一個PlatfromTransactionManager預設的隔離等級,使用資料庫預設的交易隔離等級.
另外四個與JDBC的隔離等級相對應
2. ISOLATION_READ_UNCOMMITTED: 這是事務最低的隔離等級,它充許令外一個事務可以看到這個事務未提交的資料。
這種隔離等級會產生髒讀,不可重複讀取和幻像讀。
3. ISOLATION_READ_COMMITTED: 保證一個事務修改的資料提交後才能被另外一個事務讀取。另外一個事務不能讀取該事務未提交的資料
4. ISOLATION_REPEATABLE_READ: 這種交易隔離等級可以防止髒讀,不可重複讀取。但是可能出現幻像讀。
它除了保證一個事務不能讀取另一個事務未提交的資料外,還保證了避免下面的情況產生(不可重複讀取)。
5. ISOLATION_SERIALIZABLE 這是花費最高代價但是最可靠的交易隔離等級。事務被處理為順序執行。
除了防止髒讀,不可重複讀取外,還避免了幻像讀。
spring設定檔如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- 配置交易管理員 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 配置事務的傳播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 那些類的哪些方法參與事務 -->
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* com.bjsxt.usermgr.manager.*.*(..))"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>
</beans>