Pdksock
Pdksock

Reputation: 1030

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?

Upvotes: 3

Views: 4285

Answers (2)

10Champ
10Champ

Reputation: 33

When you are referencing the method inside the same bean, the @Transaction will be ignored. These annotations are only used when referenced via Spring bean management, which will make a proxy:

https://www.javacodegeeks.com/2016/05/understanding-transactional-annotation-spring.html#:~:text=At%20a%20high%20level%2C%20when,has%20no%20knowledge%20of%20it.

So calling doOps2 doesnt do anything with the @Transactional txmanager2

Upvotes: 1

DwB
DwB

Reputation: 38290

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")

Upvotes: 5

Related Questions