Spring 事务

在xml中配置
例子:


    <!-- 1、 定义事务管理器的bean(需要注入dataSource) -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 2、 定义事务增强或事务通知(事务处理的代码,可以设置各个方法是否支持事务并配置事务属性) -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <!-- 定义事务属性,声明事务规则 -->
        <tx:attributes>
            <tx:method name="load" read-only="true"/>
            <tx:method name="list" read-only="true"/>
            <tx:method name="count" read-only="true"/>
            <tx:method name="pager" read-only="true"/>
            <tx:method name="insert" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>

            <!-- NOT_SUPPORTED 不支持事务 -->
            <tx:method name="trans00" propagation="NOT_SUPPORTED"/>
            <tx:method name="init" propagation="NOT_SUPPORTED"/>
            <tx:method name="trans01" propagation="NOT_SUPPORTED"/>
            <!-- REQUIRED 支持事务 -->
            <tx:method name="trans02" propagation="REQUIRED"/>

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

    <!-- 3、 aop配置:advisor切面————表示哪些包的哪些类的哪些方法,需要添加事务增加  -->
    <aop:config proxy-target-class="true">
        <!-- 定义切入点:包类方法 -->
        <aop:pointcut id="serviceMethod" expression="execution(* edu.uc.service..*.*(..))"/>
        <!-- 将切入点组合与事务通知 -->
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>

在使用时 抛出异常 RuntimeException(e),数据回滚

throw new RuntimeException(e)

更正:

    <!-- 去掉原来的23步骤,添加下面的第四步骤 -->
    <!-- 4.开启事务的注解驱动 -->
    <!-- transaction-manager属性的值为前面定义的事务管理器的id或名称 -->
    <!-- 如果事务管理器的id 或名称为transactionManager,则可以不写transaction-manager属性  -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

接着在需要事务处理的方法加上@Transactional

eg.

  @Transactional(propagation = Propagation.REQUIRED)
  public Long trans02(Long userA, Long userB, Long money) {}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值