Hibernate DuplicateMappingException 与来自不同数据库的 bean

Posted

技术标签:

【中文标题】Hibernate DuplicateMappingException 与来自不同数据库的 bean【英文标题】:Hibernate DuplicateMappingException with beans from different databases 【发布时间】:2020-03-27 00:08:43 【问题描述】:

编辑: 今天早上我意识到异常似乎与 Spring boot 执行器有关,该执行器似乎仅在生产中运行,而不是在从 spring 工具套件启动 prohect 时运行。 (见帖子末尾的异常跟踪)

我有一个spring boot项目,最近从1.5版本升级到2.2。

在这个项目中,我们从两个不同的数据库访问 bean。 我按照this article 中的步骤配置数据库。

使用 jpa 访问主数据库,有关此数据库的所有内容都在一个特定的包中。

另一个数据库用于直接使用休眠访问遗留 bean。这些遗留 bean 的所有内容都在不同的包中。

一些bean在两个包中具有相同的名称,但由于它们配置在两个不同的存储库中,我认为这不会有问题。

当我在 Spring Tools Suite(使用嵌入的 tomcat)中运行项目时,一切正常。

但是如果我构建一个战争并将其部署到一个独立的 tomcat(尝试使用版本 8.5 和 9)我会得到一个异常:

org.hibernate.DuplicateMappingException:[fr.mycompany.dbconfprimary.MyBean] 和 [fr.mycomany.dbconfsecondary.MyBean] 实体共享相同的 JPA 实体名称:[MyBean],这是不允许的!强>

我不明白为什么我在战争部署中遇到这个问题,但在 spring boot 嵌入式 tomcat 中却没有。

这里是主数据库的配置类:

    package fr.mycompany.dbconfprimary;

...
...

@Configuration
@EnableJpaRepositories(
        basePackages = "fr.mycompany.dbconfprimary",
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        repositoryBaseClass = BaseRepositoryImpl.class)
public class HibernatePrimaryConfig 
    ...
    ...

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
        LocalContainerEntityManagerFactoryBean em
        = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(
                new String[]  "fr.mycompany.dbconfprimary" );

        HibernateJpaVendorAdapter vendorAdapter
        = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();

        properties.put("hibernate.hbm2ddl.auto",ddlMode);
        properties.put("hibernate.dialect",dialect);
        em.setJpaPropertyMap(properties);

        return em;
    

    @Primary
    @Bean
    public PlatformTransactionManager transactionManager() 

        JpaTransactionManager transactionManager
        = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                entityManagerFactory().getObject());
        return transactionManager;
    

    @Primary
    @Bean("serversDataSource")
    public DataSource dataSource() 

        DriverManagerDataSource dataSource
          = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
       


这是辅助数据库的配置:

    package fr.mycompany.dbconfsecondary;
...
...

@Configuration
@EnableJpaRepositories(
        basePackages = "fr.mycompany.dbconfsecondary", 
        entityManagerFactoryRef = "secondaryEntityManagerFactory", 
        transactionManagerRef = "secondaryTransactionManager")
public class HibernateSecondaryConfig 
...
...

    @Bean
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory() 
        LocalContainerEntityManagerFactoryBean em
        = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(secondaryDataSource());
        em.setPackagesToScan(
                new String[] "fr.mycompany.dbconfsecondary");

        String[] hbmFiles=new String[hibernateHbmResources.length];
        for(int i=0;i<hibernateHbmResources.length;i++)
            try 
                hbmFiles[i]=convertHbmPath(hibernateHbmResources[i].getFile().getAbsolutePath());
             catch (IOException e) 
                throw(new RuntimeException(e));
            
        em.setMappingResources(hbmFiles);

        HibernateJpaVendorAdapter vendorAdapter
        = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();

        properties.put("hibernate.hbm2ddl.auto",ddlMode);
        properties.put("hibernate.dialect",dialect);
        properties.put("hibernate.current_session_context_class","thread");

        em.setJpaPropertyMap(properties);

        return em;
    

    @Bean
    public PlatformTransactionManager secondaryTransactionManager() 

        JpaTransactionManager transactionManager
        = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                secondaryEntityManagerFactory().getObject());
        return transactionManager;
    

    @Bean("secondaryServersDataSource")
    public DataSource secondaryDataSource() 

        DriverManagerDataSource dataSource
          = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
       
...
...


[几乎]完整的异常跟踪:

2019-12-11 10:08:39 [main] ERROR
                                o.s.b.w.e.tomcat.TomcatStarter - Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
2019-12-11 10:08:39 [main] INFO 
                                o.a.catalina.core.StandardService - Stopping service [Tomcat]
2019-12-11 10:08:39 [main] WARN 
                                o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2019-12-11 10:08:39 [main] INFO 
                                o.s.b.a.l.ConditionEvaluationReportLoggingListener - 
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-12-11 10:08:39 [main] ERROR
                                o.s.boot.SpringApplication - Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:156)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
    at fr.mycompany.Application.main(Application.java:41)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:126)
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:88)
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:438)
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:153)
    ... 8 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
...
    ... 13 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDiskUsage': Unsatisfied dependency expressed through field 'parameterService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterService': Unsatisfied dependency expressed through field 'paramEnumerationRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parametrageTypeEnumerationRepo': Cannot create inner bean '(inner bean)#255eadf5' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#255eadf5': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [fr/mycompany/ipolice/server/Hibernatev3Config.class]: Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
Caused by: org.hibernate.DuplicateMappingException: The [fr.mycompany.secondarydb.BeanName] and [fr.mycompany.primarydb.BeanName] entities share the same JPA entity name: [BeanName] which is not allowed!
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.addEntityBinding(InFlightMetadataCollectorImpl.java:305)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:822)
    ... 148 common frames omitted

【问题讨论】:

我认为您的 bean 名称没有正确注册。您可以尝试将其中一个数据源名称的声明从 @Bean("secondaryServersDataSource") 更改为 @Bean(name="secondaryServersDataSource") 吗? 我更正了添加 name= 属性,但不幸的是仍然是同样的错误。 【参考方案1】:

问题是您应该直接禁用默认的 Spring Data JPA 存储库初始化。

这可以通过指定spring.data.jpa.repositories.enabled=false 配置属性来实现(通过启动参数或通过application.properties

【讨论】:

我的理解是,在spring boot 2中,当你添加JPA配置类时,de spring数据存储库会被自动禁用。在 SB 1.5 中,我只需要配置辅助存储库并将默认存储库用于主数据库。无论如何,我尝试添加 enabled=false 并仍然得到相同的结果。 最近我解决了一个类似的问题***.com/questions/59006738/…。有几个问题,当我查看完整的源代码时,我能够弄清楚。如果可以接受,我们可以安排一个 15 分钟的电话,或者您可以为此分享代码。【参考方案2】:

为您的辅助 bean 分配名称,例如 @Bean("beanName")。 然后,当您想将它们注入到组件中时,您可以使用 @Qualifier("beanName")。 如果不使用限定符,则会选择主 bean 进行注入。

【讨论】:

你说的bean,你是指entitymanager?我通过 entityManagerFactoryRef = 分配名称并已经用@Qualifier 注入它。同样,当项目在 STS 中运行时,一切正常,我遇到的问题只是在战争中构建应用程序并将其部署在独立的 tomcat 中。【参考方案3】:

我终于意识到我的问题来自于主数据库使用带注释的bean,而辅助数据库使用hbm文件的事实。

当我构建项目而不是通过 Spring Tools Suite 启动项目时,似乎在类路径中找到了 Hbm 文件。

所以我的问题是在我的主存储库中定义的 bean 和在主存储库中自动加载的 hbms 中的 bean 之间存在冲突。

为了纠正这个问题,我更改了 hbm 文件的扩展名以避免主配置自动检测并修改辅助配置以搜索新的扩展名而不是 .hbm.xml。

【讨论】:

以上是关于Hibernate DuplicateMappingException 与来自不同数据库的 bean的主要内容,如果未能解决你的问题,请参考以下文章

Spring和Hibernate的注解整合 hibernate3和hibernate4/5的区别

hibernate.merge()方法怎么用

hibernate 异常 怎么解决

Hibernate之Hibernate环境配置

(转)Hibernate框架基础——Hibernate API及Hibernate主配置文件

Hibernate基础学习—Hibernate相关API介绍