Chained Transaction Manager in Spring

Suppose we have multiple databases to which we need to query under a spring transaction.

So just a @transactional annotation against a single database transaction manager won’t work.

So for multi resource, we can use XA i.e; instead of multiple transaction managers, it would be a chained transaction manager.

Using a chained transaction manager, we can issue a rollback as well against a multi db transaction.

So what is a chained transaction manager?

It is a transaction manager created against multple data sources. Consider the below example.

@Transactional(value="db1TranMgr")
public void updateDB1() {
   rep1.save();
}

@Transactional(value="db2TranMgr")
public void updateDB2() {
   rep2.save();
}

You can see 2 transaction managers which are getting used above against 2 updates against different databases.

But consider if both the updates are inside a single method, then will the transaction work?

No it won’t!!!. Because both transaction manager is specific to only one db. So one transaction manager won’t work for both db’s.

To solve this we would use chained transaction manager.

//Ceate chained transaction manager bean
@Bean (name = "chainedTransactionManager")
public ChainedTransactionManager transactionManager(@Qualifier("primaryDS") PlatformTransactionManager ds1,@Qualifier("secondaryDS") PlatformTransactionManager ds2)
{
   return new ChainedTransactionManager(ds1,ds2);
}

//Use the bean created above in a transaction involving multiple databases.

@Transactional(value="chainedTransactionManager")
public void db1(){
     rep1.save();
     updatedb2();
}

The above approach solves the multi resource transaction implementation concerns.

Thanks for reading.