Melanie
Melanie

Reputation: 93

How to configure two hibernate transactionManager for two different sessions

I have a project which deals with two different database instances. Each access to a database is transactional, but the transaction on database1 do not need to be linked to transaction on database2.

I am using Hibernate and spring-tx 4.0.3 Release, spring Ioc4 and hibernate4.

I use @Transactional annotation in my DAO services.

So I configure two datasource beans, two sessionFactory beans and two HibernateTransactionManager beans.

But doing so, I get an UniqueBeanException as the TransactionAspectSupport.determineTransactionManager tries to find only one instance of class implementing PlatformTransactionManager interface.

I have seen that I can make my java configuration class implements TransactionManagementConfigurer, so that I can specifically tell which transaction-manager bean to use, and I was hoping to implement a ProxyTransactionManager who could delegate to each appropriate transaction-manager depending on which database the current call need to be made.

The problem is implementing such ProxyPlatformTransactionManager methods, how can I know which database is being accessed, or which SessionFactory is being accessed? Otherwise I an not know which PlatformTransactionManager to use.

Has anyone faced that type of issue yet?

Thanks,

Mel

Upvotes: 0

Views: 1590

Answers (1)

smart.aleck
smart.aleck

Reputation: 225

In your application context, you need to define 2 transactionalManagers as below

<bean id="txMngr1" class="org.springframework.orm.hibernate5.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory1">
    <qualifier value="txMngr1"/>
</bean>
<bean id="txMngr2" class="org.springframework.orm.hibernate5.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory2">
    <qualifier value="txMngr2"/>
</bean>

And then use the Transactional Qualifier with your DAOs/Services.

@Transactional("txMngr2")

FYI: You can access multiple sessionFactories from your code using qualifiers as well

@Autowired
@Qualifier(value="sessionFactory2")
private SessionFactory sessionFactory;

Upvotes: 1

Related Questions