hibernate和spring的事务处理

将hibernate和spring集成,使用spring框架的声明式事务。
       使用spring的声明式事务,不再需要自动创建sessionFactory和Session,不再需要手动控制事务的开启和关闭。

       使用spring声明式事务的几个步骤:

       1. applicationContext.xml中进行配置

[html] view plain copy
 
  1. <!-- 配置事务管理器 -->      
  2. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">          
  3.      <property name="sessionFactory">              
  4.           <ref bean="sessionFactory"/>  <!-- transactionManager的SetSessionFactory()方法的参数为SessionFactory -->                     </property>      
  5. </bean>          
  6.   
  7. <!-- 那些类那些方法使用事务 -->      
  8. <aop:config>          
  9.     <aop:pointcut id="allManagerMethod" expression="execution(* com.bjpowernode.usermgr.manager.*.*(..))"/>          
  10.     <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>      
  11. </aop:config>           
  12.      
  13.   
  14. <!-- 事务的传播特性 -->        
  15. <tx:advice id="txAdvice" transaction-manager="transactionManager">          
  16.     <tx:attributes>              
  17.         <tx:method name="add*" propagation="REQUIRED"/>              
  18.         <tx:method name="del*" propagation="REQUIRED"/>              
  19.         <tx:method name="modify*" propagation="REQUIRED"/>             
  20.         <tx:method name="*" propagation="REQUIRED" read-only="true"/>          
  21.     </tx:attributes>      
  22. </tx:advice>  
[html] view plain copy
 
  1.  2.UserManagerImpl类继承HibernateDaoSupport  
[java] view plain copy
 
    1. public class UserManagerImpl extends HibernateDaoSupport{     
    2.      public void addUser(User user)       
    3.      throws Exception {          
    4.      this.getHibernateTemplate().save(user);          
    5.      log.setType("操作日志");          
    6.      log.setTime(new Date());          
    7.      log.setDetail("XXX");                   
    8.      logManager.addLog(log);                   
    9.      throw new Exception();      
    10. }  

posted on 2016-12-27 21:47  miu丶苏  阅读(157)  评论(0编辑  收藏  举报

导航