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(); }
Update
I ended up doing it differently. see here .
source share