2

We have a use-case where we want to talk to different databases which support transactions and want to do it via the annotation that spring provides.

The way I see this annotation works is that it picks the default implementation of PlatformTransactionManager with the DataSource bean defined by the client and talks to that persistence layer.

So, to talk to another data source, I will have to provide a TransactionManager which overrides its doBegin method with the help of new data source.

But the problem here is that if I do that, there is no way for the @Transaction annotation to know about which data source to pick (I am not able to see how bootstrap works in these cases because I don't see a way bean conflict could arise - maybe I am missing something here).

One alternative I can think of is to create a new annotation @DataSourceAwareTransaction which accepts a parameter for the default data source and logic gets written in the new annotation.

The issue with this approach is that I will have to change all the existing code to move from @Transaction to @DataSourceAwareTransaction.

The approach I am describing looks reasonable enough? Does anyone have any better ideas?

Thanks!

instanceOfObject
  • 2,936
  • 5
  • 49
  • 85

2 Answers2

2

But the problem here is that if I do that, there is no way for the @Transaction annotation to know about which data source to pick....

Sure there is. Have a look at @Transactional#transactionManager. The relevant section states:

transactionManager (value is an alias)
May be used to determine the target transaction manager, matching the qualifier value (or the bean name) of a specific PlatformTransactionManager bean definition.

You can specify the transaction manager that you want @Transactional to use, and the transaction manager in turn is configured for a specific data source.

Example:

@Transactional("yourTransactionManager")

or

@Transactional(value = "yourTxManager", isolation = ..., propagation = ...)

Where your transaction manager bean definition looks something like this:

@Bean
public PlatformTransactionManager yourTxManager() {
    return new JpaTransactionManager(entityManagerFactory().getObject());
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
0

Please see the answer in this post I think it is exactly what you are looking for, multiple transaction managers using a qualifier to tell @Transactional which transaction manager to use.

Spring - Is it possible to use multiple transaction managers in the same application?

crabe
  • 322
  • 4
  • 15