With Spring @Transactionnal, how does Spring know which data source to use?

When using @Transactionnal with Spring

  • How to choose a data source on which it should open a transaction?

  • Is there some kind of magic trick like proxies, threads or something else?

  • If so, then these tricks work with any JDBC library (for Hibernate it works, but what about MyBatis?)

  • What if there are 2 data sources?

  • But what if I call @Transactionnal service, a DAO with two basic different data sources? Will it be transactional for both data sources or only for one of them or will it fail?

thanks

+4
source share
2 answers

To use multiple transaction handlers, simply specify the qualifier and specify it. For two different DAOs with two different data sources, you will need two different transaction managers. And, of course, transactions should go through your classes of service, and not through the DAO directly. The same for any type of transactionmanager - it is hibernation or a plain old jdbc.

<bean id="transactionManagerOne" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactoryOne"> <qualifier value="One" /> </bean> 

and factory session

 <bean id="sessionFactoryOne" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSourceOne" 

and just configure the data source with the identifier dataSourceOne, then you will bind the transaction statement to the code with the name of the qualifier:

 @Transactional(value = "One") 
+3
source

I can provide a partial response, which is usually used when using the PlatformTransactionManager from Spring, it was associated with one data source when it was created. Something like that:

 @Bean public PlatformTransactionManager txManager() { return new HibernateTransactionManager(sessionFactory()); } 

SessionFactory configured on a data source. I suspect that if you want to have a few PlatformTransactionManager , then you can not just rely on their outsourcing as beans, as I have done above. You may need to use the TransactionTemplate class and code at a slightly lower level.

+1
source

Source: https://habr.com/ru/post/1440074/


All Articles