springboot jpa 配置多数据源报错解决 Consider defining a bean named ‘entityManagerFactory‘

编程知识 更新时间:2023-05-02 05:20:50

版本

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‘

本文发布于:2023-04-26 05:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/3810c56893ab479605c78ec00ba49b86.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:报错   jpa   springboot   defining   entityManagerFactory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 104291文章数
  • 26210阅读数
  • 0评论数