在Myeclipse 8.6寫一個基於SSH的應用時遇到如下問題:
在JUint中寫UserDAOImpl的txsaveNewUser方法測試時,執行一切正常,可是查看mysql數據庫中是一片空白,數據並沒有插入到數據庫中。UserDAOImpl用的是HibernateTemplate的save方法,應當是沒什麼問題的,最終發現是如下問題所致:
Spring對聲明式事務的支持配置。
之前爲了業務邏輯處理的連貫性,將事務管理配置在了service層,如下:
<!-- TransactionManager配置 -->
<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="tx*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 聲明式事務AOP配置 -->
<aop:config>
<aop:pointcut id="allservice" expression="execution(public * fanfan.service..*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="allservice"/>
</aop:config>
可是這次測試是在DAOImpl層開展的,故沒有將此納入事務管理,出現了問題。
解決辦法:
將DAOImpl層也配置進事務的管理,具體配置如下:
<!-- TransactionManager配置 -->
<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="tx*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 聲明式事務AOP配置 -->
<aop:config>
<aop:pointcut id="allservice" expression="execution( public * fanfan.service..*(..))"/>
<aop:pointcut id="daomethods" expression="execution( public * fanfan.DAOImpl..*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="allservice"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="daomethods"/>
</aop:config>
這樣,在測試DAOImpl時就納入了事務的管理,測試正常。
在運行階段,service層就會打開事務,而propagation="REQUIRED"的配置也會保證DAOImpl會用已經開啓的事務進行操作,問題得到解決。