Java EE进阶之Spring事务深入浅出

发表于:2011-1-28 09:50

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:yingzhor    来源:51Testing软件测试网采编

#
java
#
JAVA
#
Java

  一、在Spring中配置事务管理器

  1、事务管理器bean的声明。

  • <bean id="transactionManager"     
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">    
  •    <property name="sessionFactory" ref="sessionFactory" />    
  • bean>
  •   2、如果你需要以标注驱动的方式管理的话,必须在applicationContext.xml中申明。

    <tx:annotation-driven transaction-manager="transactionManager"/>

      3、如果你用xml的方式使用事务管理器的话,如下有一个例子。

  • <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
  •     <tx:attributes> 
  •         <tx:method name="find*" read-only="true"/> 
  •         <tx:method name="*" propagation="REQUIRED"/> 
  •     tx:attributes> 
  • tx:advice> 
  • <aop:config> 
  •     <aop:pointcut expression="execution(* *..dao.impl..*(..))" id="dao-pc"/> 
  •     <aop:pointcut expression="execution(* *..service.impl..*(..))" id="service-pc"/> 
  •     <aop:advisor advice-ref="txAdvice" pointcut-ref="dao-pc"/> 
  •     <aop:advisor advice-ref="txAdvice" pointcut-ref="service-pc"/> 
  • aop:config> 
  • <aop:aspectj-autoproxy />
  •   二、在java代码中指定事务属性(使用标注)

      下面例子是Dao实现类的一个方法,采用标注来指明事务。

  • @Transactional(readOnly=true)  
  • public List<User> findUser(UserDto dto) {  
  •     User user = new User();  
  •     BeanUtils.copyProperties(dto, user);  
  •     return factory.getCurrentSession()  
  •         .createCriteria(User.class)  
  •         .add(Example.create(user))  
  •         .list();  
  • }
  •   三、Spring事务选项1.默认的 @Transactional设置如下

      · 事务传播设置是 PROPAGATION_REQUIRED 使用现有事物,没有则启动新事物

      · 事务隔离级别是 ISOLATION_DEFAULT

      · 事务是 读/写 false

      · 事务超时默认是依赖于事务系统的,或者事务超时没有被支持。

      · 任何unchecked Exception将触发事务回滚,但是任何checked Exception将触发事务提交

    21/212>
    《2023软件测试行业现状调查报告》独家发布~

    关注51Testing

    联系我们

    快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

    法律顾问:上海兰迪律师事务所 项棋律师
    版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
    投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

    沪ICP备05003035号

    沪公网安备 31010102002173号