How to configure transaction management for working with 2 different db in Spring?

Roman picture Roman · Dec 25, 2009 · Viewed 44.2k times · Source

I have 2 databases (MySql and HSQLDB). I configured 2 data sources and 2 EntityManagerFactory beans. I can also configure 2 correspondent JpaTransactionManager beans.

But I don't know how to specify which of them should be used to manage transactions for concrete service-class. I want to use @Transactional annotation for that purpose, but I actually can specify only one of txManagers:

<tx:annotation-driven transaction-manager="manager"/>

What is the way out from this situation?

Answer

axtavt picture axtavt · Dec 25, 2009

Declare your <tx:annotation-driven> without transaction-manager attribute, declare qualifiers for transaction managers like this:

<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <qualifier value="txManager1"/>
</bean>

Use this qualifier in @Transactional as a value to select one of transaction managers:

@Transactional("txManager1")

or, with more properties:

@Transactional(value = "txManager1", readOnly = true)