Transactional的annotation版和xml版

添加用户和添加事物管理两个方法在两个事物中,不好管理

 @Transactional 注解的属性

xmlns:tx=http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx

          http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="txManager"

       class="org.springframework.orm.hibernate3.HibernateTransactionManager"><!—切面类-->

              <property name="sessionFactory" ref="sessionFactory"/><!--用数据库连接管理事物sessionFactory-->

</bean>

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

关系梳理dataSource—》sessionFactory—》txManager—》事物的管理交给txManager

默认捕捉到的是runtime的异常,它会自动回滚,这时Session只能sessionFactory.getCurrentSession();,因为Hibernate中事物默认是thread的,所以可以看出事物自动加上,一但有异常不会增加记录,若没有spring管理代码应该这么写

try {

                     userDAO.save(u);

                     Log log=new Log();

                     log.setMsg("a user saved!");

                     logDAO.save(log);

              } catch (Exception e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

有了spring管理我们只需关心逻辑管理

userDAO.save(u);

              Log log=new Log();

              log.setMsg("a user saved!");

              logDAO.save(log);

查阅资料:

propagation

public abstract Propagation propagation

The transaction propagationtype.

Defaults to Propagation.REQUIRED.

Default:

org.springframework.transaction.annotation.Propagation.REQUIRED

propagation是一个枚举类型

事务传播设置是 PROPAGATION_REQUIRED,事务的产生过程

默认值REQUIRED

MANDATORY调用之前就必须存在一个事物,没有会报错

NESTED内嵌的,内部的执行完,外部在执行

NEVER必须没有事物

NOT_SUPPORTED有事物先挂起

REQUIES_NEW有事物先挂起,创建一个新的

SUPPORTS不用记

Xml:

因为用的是Hibernate:

<bean id="txManager"

       class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <property name="sessionFactory"ref="sessionFactory" />

</bean>

在哪儿:

    <aop:config>

       <aop:pointcut id="bussinessService"expression="execution(public *com.*.service..*.*(..))"/>

       <aop:advisor advice-ref="txAdvice"pointcut-ref="bussinessService"/>给了个建议,在service加建议,建议写在txAdvice

      

    </aop:config>

    加什么:

    <tx:advice id="txAdvice" transaction-manager="txManager">

       <tx:attributes>

           <tx:method name="get*"read-only="true"/>

           <tx:method name="add*"propagation="REQUIRED"/>

       </tx:attributes>

    </tx:advice>

好处不要不需要在每个方法上加trasational

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值