0

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

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Melanie
  • 93
  • 1
  • 9
  • Simply specify in the [`@Transactional`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#value--) annotation which tx manager it applies to and spring will do it for you. No need for additional classes. – M. Deinum Jun 18 '14 at 05:21
  • Thanks Deinum, I did think about that :) But unfortunately, some of my Hibernate objects are defined in some jar libraries. So If I use this approach, I need to hack all those classes in order to input the appropriate tx manager. Unless maybe there is a way to set the default tx manager to one of the bean ? – Melanie Jun 19 '14 at 05:48

1 Answers1

1

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;
smart.aleck
  • 195
  • 1
  • 7