版本
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 {...}
更多推荐
springboot jpa 配置多数据源报错解决 Consider defining a bean named ‘entityManagerFactory‘
发布评论