Search code examples
javaspringspring-dataspring-transactions

Nested transactions with different transaction managers in spring


I am trying to nest transactions with different transaction managers wherein if the nested transaction fails the outer main transaction needs to rollback as well

    @Transactional(transactionManager = "txManager1", propagation = Propagation.REQUIRED)
    public int doOps() {
         doSuccessfulDatabaseThings();
         doOps2();
    }

    @Transactional(transactionManager = "txManager2", propagation = Propagation.REQUIRED)
    public int doOps2() {
        //this throws error
    }

My spring config file has

<bean id="dataSource1" class ="com.mchange.v2.c3p0.ComboPooledDataSource">
...
</bean>

<bean id="txManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource1" />
</bean>
<!-- txManager2 defined similarly -->
<tx:annotation-driven/>

However, when doOps2() fails, the transaction in doOps() doesn't rollback. How to make the rollback work?


Solution

  • Bold Statement
    You're doing it wrong.

    Based on you description, you want a ChainedTransactionManager.

    Create a transaction manager for each of your datasources, then pass the transaction manager to the ChainedTransactionManager constructor. Name the ChainedTransactionManager bean and reference the name in a @Transactional annotation. I think the property is named "transactionManager". For example,
    @Transactional(transactionManager = "chainedTransactionManagerBeanName")