Multiple Transaction Managers in Spring Download for Different EntityManagers

I need to connect to two different databases from one application. The problem is that my appEntityManager does not have a transaction manager associated with it, and I'm not sure how to do it. @Primary adminEntityManager can use the one provided on spring boot without any problems, as described here .

The configuration above almost works on its own. To complete you need to configure the TransactionManager for the two EntityManagers as well. One of them can be selected by default JpaTransactionManager in spring Download if you marked it as @Primary. others must be explicitly entered into the new instance. Or you could use a JTA transaction manager covering both.

I recorded the configuration with

@EnableTransactionManagement 

And here is the relavant beans

 @Bean @ConfigurationProperties(prefix = "datasource.app") public DataSource appDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary @ConfigurationProperties(prefix = "datasource.admin") public DataSource adminDataSource() { return DataSourceBuilder.create().build(); } @Bean public LocalContainerEntityManagerFactoryBean appEntityManagerFactory( final EntityManagerFactoryBuilder builder) { return builder .dataSource(appDataSource()) .packages("au.com.mycompany.app.bomcommon.domain") .persistenceUnit("appPersistentUnit") .build(); } @Bean @Primary public LocalContainerEntityManagerFactoryBean adminEntityManagerFactory( final EntityManagerFactoryBuilder builder) { return builder .dataSource(adminDataSource()) .packages("au.com.mycompany.app.bombatch") .persistenceUnit("adminPersistentUnit") .build(); } //I thought this would do it but I am getting an exception //No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: appTransactionManager,transactionManager @Bean public JpaTransactionManager appTransactionManager(@Qualifier("appEntityManagerFactory") final EntityManagerFactory emf) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(emf); return transactionManager; } 

Update

I ended up doing it differently. see here .

+5
source share
1 answer

See if this works:

 @Bean @Primary @ConfigurationProperties(prefix = "datasource.admin") public DataSource adminDS() { ... } @Bean @Primary public LocalContainerEntityManagerFactoryBean adminEMF(...) { ... } @Bean @Primary public JpaTransactionManager adminTM(...) { ... } @Bean public LocalContainerEntityManagerFactoryBean appEMF(...) { ... } @Bean public JpaTransactionManager appTM(...) { ... } 

The only change I made from your configuration is to declare the transaction manager for the admin side explicitly and note that the transaction manager is the default.

+4
source

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


All Articles