java - Spring事务配置在service层,传播规则为required,方法中究竟应该是调用service还是多个dao比较好?
迷茫
迷茫 2017-04-18 10:56:29
0
3
627

Spring中事务配置如下:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="delete*" propagation="REQUIRED" read-only="false" 
                   rollback-for="java.lang.Exception"/>
        <tx:method name="insert*" propagation="REQUIRED" read-only="false" 
                   rollback-for="Exception" />
        <tx:method name="update*" propagation="REQUIRED" read-only="false" 
                   rollback-for="java.lang.Exception" />
        <tx:method name="save*" propagation="REQUIRED" read-only="false" 
                   rollback-for="Exception" />
        <tx:method name="*" propagation="REQUIRED" read-only="true"/>
    <:attributes>
<:advice>

现在ServiceA中有一个方法methodA,那么在ServiceA中应该注入ServiceB,ServiceC呢,还是DaoB,DaoC,然后在methodA中去保存B,C,保证B,C同时保存成功,或同时失败!


答:

既可以单独注入service,也可以单独注入dao,关键是,spring容器的事务管理默认只截获未检查异常RuntimeException。上边配置的rollback-for="java.lang.Exception"其实不用配置。配置如下

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="delete*" propagation="REQUIRED" read-only="false"  />
        <tx:method name="insert*" propagation="REQUIRED" read-only="false"   />
        <tx:method name="update*" propagation="REQUIRED" read-only="false"   />
        <tx:method name="save*" propagation="REQUIRED" read-only="false"  />
        <tx:method name="*" propagation="REQUIRED" read-only="true"/>
    <:attributes>
<:advice>

解决方案是:

  • 如果代码中使用了try...catch...捕获了检查型异常,意味着程序员自己必须要解决异常,必须知道如何解决异常。通常的做法是:将检查型的异常在catch块中重新抛出为Runtime Exception,这样Spring容器就会截获该异常,进行事务回滚处理 。如下

try {
   .....
}catch( CheckedException e ) {
    logger.error(e);
    throw new RuntimeException(e);
}

注意,不使用try...catch...,而在方法签名后向外抛出检查型异常的行为不可取,事务也不会回滚。

  • 如果代码中没有使用try抛出了未检查异常,则Spring容器会自动截获异常,进行事务回滚处理。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
伊谢尔伦

If you want to know more about Spring transaction mechanism, you can read these articles of mine:

  1. Detailed explanation of Spring Transaction - Transaction Isolation

  2. Detailed explanation of Spring Transaction - Transaction Propagation mode

  3. Detailed explanation of Spring Transaction - Manual rollback of transactions

  4. Detailed explanation of Spring Transaction - transaction rollback mechanism when exceptions occur

Peter_Zhu

In fact, this kind of thing is done according to needs, and transactions will be automatically merged. However, as a design consideration, try to call dao so that different services can be uncoupled.

黄舟

Generally, it is more complicated for us in Service的方法上会进行事务的定义,特别是如果有控制传播行为的场景,那放入dao就和放入service不同了。因为dao肯定都是在一个大事务下了,service.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!