springboot 2.6.x
jpa配置多数据源后启动报错
Consider defining a bean named ‘entityManagerFactory’
方法1:将其中一个datasource添加@Primary注解 方法2:自行定义entityManagerFactory
private static JpaVendorAdapter jpaVendorAdapter(JpaProperties properties) {
AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(properties.isShowSql());
if (properties.getDatabase() != null) {
adapter.setDatabase(properties.getDatabase());
}
if (properties.getDatabasePlatform() != null) {
adapter.setDatabasePlatform(properties.getDatabasePlatform());
}
adapter.setGenerateDdl(properties.isGenerateDdl());
return adapter;
}
@Bean
public EntityManagerFactoryBuilder entityManagerFactoryBuilder(
ObjectProvider<PersistenceUnitManager> persistenceUnitManager,
ObjectProvider<EntityManagerFactoryBuilderCustomizer> customizers
) {
EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(
jpaVendorAdapter(jpaProperties()),
this.jpaProperties().getProperties(),
(PersistenceUnitManager) persistenceUnitManager.getIfAvailable()
);
customizers.orderedStream().forEach((customizer) -> {
customizer.customize(builder);
});
return builder;
}
springboot jpa自动配置需要存在单一候选DataSource时才会生效 org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(HibernateProperties.class)
@ConditionalOnSingleCandidate(DataSource.class)
class HibernateJpaConfiguration extends JpaBaseConfiguration {...}