2017-05-27 61 views
0

在我的項目中,我需要在一個事務中處理更多的數據庫。交易註釋或xml

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> 

回答

0

Java不允許在同一元素上使用同一類型的多個註釋,除非註釋是(甲基)與@Repeatable -annotated:Multiple annotations of the same type on one element?

但是Transactional不是(甲基)與@Repeatable -annotated,因此僅的@Transactional一個實例是允許在一個類型或方法。

在這種情況下,您必須使用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
+0

我要回滾所有交易,如果這兩個交易中的任何一個失敗。在我的方式,兩個transations如下:
'(1)爲Transaction1開始' '(2)transaction2開始' '(3)我的業務邏輯代碼' '(4)交易2端' '(5 )transaction1結束' 所以在1-4之間引發任何異常,兩個事務將回滾。唯一的飛行是(4)和(5)之間拋出的異常,只有外部事務將回滾 ,但內部事務將提交.'@Roman Puchkovskiy' –

+0

請注意我關於XT Transaction的編輯 –