spring3+hibernate4.1聲明式事務

 

 spring使用的jar包如下

 

hibernate使用的jar包如下:

 

 

 

Spring使用的spring3.1.1,hibernate使用的4.1.0版本。

applicationContext.xml配置如下:

<!-- define PlatformTransactionManager (declarative transaction)  -->
 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory"/>
  </bean>
  
  <!-- ensure that the above transactional advice runs for any execution
    of an operation defined by the FooService interface -->
  <aop:config>
   <aop:pointcut expression="execution(* com.henu.strawhat.service.impl.*.*(..))" id="myPointcut"/>
   <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
  </aop:config>
  
  <!-- config the transactionnal advice -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- the transactional semantics... -->
     <tx:attributes> 
      <!-- all methods starting with 'get' are read-only --> 
        <tx:method name="get*" read-only="true"/>
        <!-- other methods use the default transaction settings (see below) -->
      <tx:method name="save" propagation="REQUIRED"/>
     </tx:attributes>
</tx:advice> 


 

Spring3有兩種事務處理配置;一種是基於xml的聲明式事務管理。另外一種是基於@Transaction的聲明式事務管理。本文主要是針對前者進行配置。

下面是DAO持久層代碼:

現在在applicationContext中去掉此項。
但是又出現其他問題。
org.hibernate.TransactionException: nested transactions not supported
又查了資料,原來Hibernate根本就不支持Nested Transaction,最新的Hibernate4也是如此。在配置文件中設置"nestedTransactionAllowed=true",其實只對JDBC事務起效(如使用Spring的JdbcTemplate)。 經過測試,Hibernate框架託管下的Nested Transaction方法(子事務)拋出異常時,Spring日誌會提示Rolling back transaction to savepoint,不過所謂“回滾”的是使用JDBC操作的內容,如果事務中沒有JDBC操作等於是沒有效果的。子事務操作會被保存到Hibernate的緩存中,並在下一次flush時被提交。 
解決方法是去掉

session.beginTransation();

session.getTransaction().commit();

這樣問題就解決了!
至於這裏面的深層含義,我正在琢磨中,到下一篇給大家做詳細介紹。

使用的getCurrentSession();方法。
官方文檔中說最新的Hibernate已經不需要用戶自己使用ThreadLocal得方式來管理和持有session,,而把這種session管理方式內置了,只要依據依據配置就可以用了 
所遇到的問題:
第一個問題,使用junit,調試程序出現。
org.hibernate.HibernateException: save is not valid without active transaction
的錯誤。
查了很多資料才發現這個問題。
以往在配置中使用
發佈了18 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章