加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

使用Annotation进行声明式事务管理

(2011-12-29 14:32:50)
标签:

it

分类: Spring

事务加在DAO层还是Service层? service

使用     annotation

  i.          加入annotation.xsd

  ii.          加入txManager bean

  iii.          <tx:annotation-driven

  iv.          在需要事务的方法上加:@Transactional

   v.          需要注意,使用SessionFactory.getCurrentSession 不要使用OpenSession

   @Transactional详解

      什么时候rollback 

     运行期异常,非运行期异常不会触发rollback

    必须uncheck (没有catch)

    不管什么异常,只要你catch了,spring就会放弃管理

    事务传播特性:propagation_required 默认

当这个方法没有事务时,创建一个

当这个方法有事务时,用当前的

 

    read_only 做查询时,Connection(只读)提高性能

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx
          
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
 <context:annotation-config />
 <context:component-scan base-package="org.spring" />

 

 <bean id="txManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="mySessionFactory" />
 </bean>
 <tx:annotation-driven transaction-manager="txManager"/>
</beans>

 

UserService中: 保存User后,还需记录日志,两个方法放在一个事务中处理

 @Transactional

 public void add(User user) {
  
   userDAO.save(user);
   Log log = new Log();
   log.setMsg("a user saved!");
   logDAO.save(log);
  
 }

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有