我需要从一个应用程序连接到两个不同的数据库.问题是我的appEntityManager没有与之关联的事务管理器,我不知道该怎么做. @Primary adminEntityManager能够使用spring boot提供的那个,没有任何问题,如here所述.
The configuration above almost works on its own. To complete the
picture you need to configure TransactionManagers for the two
EntityManagers as well. One of them could be picked up by the default
JpaTransactionManager in Spring Boot if you mark it as @Primary. The
other would have to be explicitly injected into a new instance. Or you
might be able to use a JTA transaction manager spanning both.
我已经注释了配置
@EnableTransactionManagement
这是相关的豆子
@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;
}
更新
我最后以不同的方式做到了这一点. see here.
最佳答案
看看这是否有效:
@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(...) { ... }
我对您的配置进行的唯一更改是明确声明管理端的事务管理器,并将该事务管理器标记为默认值.