簡體   English   中英

如何在Spring Boot中通過jdbcTemplate將單個事務與多個數據源一起使用?

[英]How can I use single transaction with multiple datasources with jdbcTemplate in spring boot?

我需要回滾第一條語句,如果在不同的數據庫中執行第二條更新語句時有任何錯誤。 我不想使用EntityManager,因為在所有其他代碼中已經使用了JdbcTemplate。 如果我將@Transactional與限定符一起使用,則效果很好,但我希望@Transactional應該對兩個數據庫都適用。

我的代碼段如下:

**DatasourceConfig.xml**
//Datasource for **DB2** database
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfigLmsDataSource" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  scope="singleton" primary="true">
  <property name="dataSource" ref="dataSource" />
</bean> 

//Datasource for **Mysql** Database database
<bean id="dataSource1" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfigLmsDataSource1" />
</bean>

<bean id="jdbcTemplate1" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource1"/>
</bean>

<bean id="transactionManager1"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  scope="singleton" primary="true">
  <property name="dataSource" ref="dataSource1" />
</bean>


//Inside service class
**MyService.java**

@Autowired("jdbcTemplate")
JdbcTemplate jdbcTemplate;

@Autowired("jdbcTemplate1")
JdbcTemplate jdbcTemplate1;

@Transactional
public void modifyDB()
{
    jdbcTemplate.update("Update query for table in DB2 database");
    jdbcTemplate1.update("Update query for table in MySql database");
}

您需要一名全球交易經理。 您可以使用Spring的JtaTransactionManager

這是顯示它的教程:

http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM