title: Spring Boot: Transaction with two DB, rollback first DB if second DB fails
body: <p>I am building a Spring Boot application that has two datasources. I need to make an update in DB1 and then in DB2. But if DB2's update fails, DB1 update should rollback. </p>
  
  <p>I have seen <a href="https://stackoverflow.com/questions/48954763/spring-transactional-with-a-transaction-across-multiple-data-sources">a post</a> with the same problem but the <code>ChainedTransactionManager</code> implementation doesn't work for me. </p>
  
  <p>My current implementation is:</p>
  
  <p>I have 2 beans with different datasources for the transaction managers:</p>
  
  <pre class="lang-xml prettyprint-override"><code>    &lt;bean id="dataSourceTransactionManagerSP" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" primary="true"&gt;
          &lt;constructor-arg ref="dataSourceSP"/&gt;
      &lt;/bean&gt;
  
      &lt;bean id="dataSourceTransactionManagerBOL" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;
          &lt;constructor-arg ref="dataSourceBOL"/&gt;
      &lt;/bean&gt;
  </code></pre>
  
  <p>I have two transactional methods that make the updates. For some weird reason the <code>@Transactional</code> annotation didn't work in any method. But so far, these two methods works well within its datasource.</p>
  
  <p>For first DB:</p>
  
  <pre class="lang-java prettyprint-override"><code>    @Override
      public Boolean updateDB1() {
          transactionTemplate.setTransactionManager(dataSourceTransactionManagerSP);
          return transactionTemplate.execute(status -&gt; {
              boolean r1 = repository1.update1();
              boolean r2 = repository1.update2();
              return r1 &amp;&amp; r2;
          });
      }
  </code></pre>
  
  <p>For second DB:</p>
  
  <pre class="lang-java prettyprint-override"><code>    @Override
      public Boolean updateDB2() {
          transactionTemplate.setTransactionManager(dataSourceTransactionManagerBOL);
          return transactionTemplate.execute(status -&gt; {
              boolean r1 = repository2.update1();
              boolean r2 = repository2.update2();
              return r1 &amp;&amp; r2;
          });
      }
  </code></pre>
  
  <p>But now I need a method that calls <code>updateDB1</code> and <code>updateDB2</code> and if DB2 fails, DB1 rollbacks.</p>
  
  <pre class="lang-java prettyprint-override"><code>    @Override
      public Boolean updateBoth() {
  
          return transactionTemplate.execute(status -&gt; {
              boolean r1 = updateDB1();
              boolean r2 = updateDB2();
              return r1 &amp;&amp; r2;
          });
      }
  </code></pre>
  
  <p>I know that this won't work because I need to specify the TransactionManager, but this is the problem, I have two transaction managers.</p>