事务注释或xml

时间:2017-05-27 09:42:43

标签: java spring transactions transactional

在我的项目中,我需要在一个事务中处理更多数据库。

1:使用注释,报告错误"重复注释"

public class TransactionalService {

@Transactional("order")
@Transactional("account")
public void processTwoDatabases(String name) { ... }

}

xml段如下  

<bean id="transactionManager1"
       class="org.springframework.jdbc.DataSourceTransactionManager">
      <qualifier value="order"/>
</bean>
<bean id="transactionManager2" 
        class="org.springframework.jdbc.DataSourceTransactionManager">
       <qualifier value="account"/>
</bean>  

2:但是使用xml,它可以正常工作:

<tx:advice id="txAdvice1" transaction-manager="transactionManager1">
    <!-- 定义方法的过滤规则 -->
    <tx:attributes>
        <tx:method name="process*" propagation="REQUIRED" read-only="false"
                   rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>


<aop:config proxy-target-class="true">
    <aop:pointcut expression="execution (* com.service.impl.*.*(..))" id="services1"/>
    <aop:advisor advice-ref="txAdvice1" pointcut-ref="services1"/>
</aop:config>


<tx:advice id="txAdvice2" transaction-manager="transactionManager2">
    <tx:attributes>
        <tx:method name="process*" propagation="REQUIRED" read-only="false"
                   rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>


<aop:config proxy-target-class="true">
    <aop:pointcut expression="execution (* com.service.impl.*.*(..))" id="services2"/>
    <aop:advisor advice-ref="txAdvice2" pointcut-ref="services2"/>
</aop:config>

1 个答案:

答案 0 :(得分:0)

Java不允许在同一元素上使用相同类型的多个注释,除非注释使用0进行(元)注释:Multiple annotations of the same type on one element?

但是@Repeatable不是{meta}注释Transactional,因此在类型或方法上只允许@Repeatable的一个实例。

在这种情况下你必须使用XML。

但请注意,您没有获得一笔交易。实际上,您可以获得两个不同的事务,每个事务管理器一个。

此外,您没有在事务管理器定义中指定任何数据源,因此它们都使用相同的数据源(以及相同的数据库)。

要实际拥有一个交易,您可能需要XA交易支持。以下是一些链接:

  1. http://www.javaworld.com/article/2077714/java-web-development/xa-transactions-using-spring.html
  2. http://www.javaworld.com/article/2077963/open-source-tools/distributed-transactions-in-spring--with-and-without-xa.html
  3. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-jta.html