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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章