Home  >  Q&A  >  body text

java - Spring事务配置在service层,传播规则为required,方法中究竟应该是调用service还是多个dao比较好?

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( CheckedException e ) {
    logger.error(e);
    throw new RuntimeException(e);
}

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

迷茫迷茫2742 days ago625

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:58:29

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:58:29

    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.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:58:29

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

    reply
    0
  • Cancelreply