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

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


Where you use a @Transactional annotation, you can specify the transaction manager to use by adding an attribute set to a bean name or qualifier. For example, if your application context defines multiple transaction managers with qualifiers:

<bean id="transactionManager1"    class="org.springframework.orm.jpa.JpaTransactionManager">    <property name="entityManagerFactory" ref="entityManagerFactory1" />    <qualifier value="account"/></bean><bean id="transactionManager2"    class="org.springframework.orm.jpa.JpaTransactionManager">    <property name="entityManagerFactory" ref="entityManagerFactory2" />    <qualifier value="businessData"/></bean>

You can use the qualifier to specify the transaction manager to use:

public class TransactionalService {    @Transactional("account")    public void setSomethingInAccount() { ... }    @Transactional("businessData")    public void doSomethingInBusinessData() { ... }}


This Spring Jira entry discusses the issue a bit:

https://jira.spring.io/browse/SPR-3955

I think it could be one transaction manager per connection if you're not using two-phase commit. You just need to create two transaction managers and inject them with the appropriate connection.

But I must ask the question: why do you think you need two transaction managers? You can have more than one database connection. The DAOs that use the connections can and should be instantiated by different services, each of which can be annotated with their own transactional settings. One manager can accommodate both. Why do you think you need two?