為保證資料一致性,編程時往往要引入事務。事務有四個特性:原子性、一致性、隔離性、持久性;種類則分編程式事務(寫在程式碼裡)與聲明式事務(透過設定檔或註解)。Spring 的強項正是後者。
不論用哪一種寫法,都逃不出這四件事:
第一種是指向既有的 hibernate.cfg.xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
第二種是在 Spring 設定檔中手動配置資料源(需額外引入 commons-dbcp 與 commons-pool):
<!-- 2.1 資料源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate_cache"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<!-- 2.2 SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:實體對應 xml 的路徑</value>
</list>
</property>
</bean>
至此 SessionFactory 已交由 Spring 管理,接著才是事務的問題。
<!-- 事務容器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事務規則 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 事務入口 -->
<aop:config>
<aop:pointcut id="allDaoMethod"
expression="execution(* com.jianxin.dao.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethod" />
</aop:config>
<!-- 事務容器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事務規則 -->
<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<!-- 以 - 表示回滾,+ 表示不回滾 -->
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,+MyException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">READONLY</prop>
</props>
</property>
</bean>
<!-- 事務入口 -->
<bean id="userDaoProxy" parent="transactionProxy">
<property name="target" ref="userDao"/>
</bean>
tx:advice + AOP 的寫法把規則集中在一處,介面一改只要動設定檔,適合方法眾多的 DAO 層;代理的方式則每個 bean 都要掛一次 parent,顯得囉嗦,但對「哪些方法要回滾哪些不要」能做更細顆粒的控制。實務上新專案多半走註解(@Transactional)路線,不過理解這兩種 XML 寫法,對接手老專案很有幫助。
延伸:Hibernate 中文手冊 PDF https://www.linuxidc.com/Linux/2013-10/91208.htm