Проблема с несколькими источниками данных при загрузке Spring - IllegalArgumentException: имя не может быть пустым - PullRequest
2 голосов
/ 04 февраля 2020

Я пытаюсь подключиться к двум базам данных в Spring boot 2. Одна - MySQL, а другая - DB2. Если я использую только MySQL, я могу подключиться к нему и успешно выполнить запрос к базе данных. Однако, если я добавляю вторичную базу данных в мое приложение, во время запуска приложения происходит сбой создания entityManagerFactory, и возникает жалоба на «Имя не может быть пустым». Я не уверен, что именно мне не хватает.

Ниже приведена трассировка стека исключений при запуске приложения

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: dss] Unable to build Hibernate SessionFactory; nested exception is java.lang.IllegalArgumentException: Name cannot be null
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 16 common frames omitted
Caused by: java.lang.IllegalArgumentException: Name cannot be null
    at org.hibernate.boot.model.relational.QualifiedNameParser$NameParts.<init>(QualifiedNameParser.java:35) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.boot.model.relational.QualifiedNameImpl.<init>(QualifiedNameImpl.java:24) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.boot.model.relational.QualifiedSequenceName.<init>(QualifiedSequenceName.java:16) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:51) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:65) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:59) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:132) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:96) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) ~[hibernate-core-5.3.11.Final.jar:5.3.11.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 20 common frames omitted

И ниже приведены мои конфигурации в application.properties

#DB1 Details:
spring.datasource.url=jdbc:mysql://SE140009.DEV.DEVFG.abc.COM:3306/payment_local?autoReconnect=true&useSSL=false
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=ABCD
spring.datasource.password=xxxx
#spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

#DB2 Details
spring.dss-datasource.url=jdbc:db2://cp2.fg.abc.com:50002/DB0ZZCC:securityMechanism=9;encryptionAlgorithm=2;
spring.dss-datasource.driverClassName=com.ibm.db2.jcc.DB2Driver
spring.dss-datasource.username=TZM2SRVC
spring.dss-datasource.password=xxxxx
 # Keep the connection alive if idle for a long time (needed in production) 
spring.dss-datasource.testWhileIdle=true 
spring.dss-datasource.validationQuery=SELECT 1 
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DB2Dialect```

**And here are my config classes**

    ```@Configuration
       @EnableTransactionManagement
       @EnableJpaRepositories(
            entityManagerFactoryRef = "entityManagerFactory",
            transactionManagerRef = "dssTransactionManager",
            basePackages = {
            "com.abc.sam.account.dss.repository" })
    public class DSSDBConfig {

        @Bean(name = "dssDataSourceProperties")
        @ConfigurationProperties("spring.dss-datasource")
        public DataSourceProperties dataSourceProperties() {
            return new DataSourceProperties();
        }

        @Bean(name = "dataSource")
        @ConfigurationProperties("spring.dss-datasource.configuration") 
        public DataSource dataSource(@Qualifier("dssDataSourceProperties")
        DataSourceProperties dssDataSourceProperties) { 
            return dssDataSourceProperties.initializeDataSourceBuilder().build(); 
        }

        @Bean(name = "entityManagerFactory")
        public LocalContainerEntityManagerFactoryBean entityManagerFactory(
                EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {

            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("hibernate.dialect", "org.hibernate.dialect.DB2Dialect");
            return builder
                    .dataSource(dataSource)
                    .packages("com.abc.sam.account.dss.model")
                    .persistenceUnit("dss")
                    .properties(properties)
                    .build();
        }

        @Bean(name = "dssTransactionManager")
        public PlatformTransactionManager transactionManager(
                @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
            return new JpaTransactionManager(entityManagerFactory);
        }

    }```


    ```@Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
            entityManagerFactoryRef = "receiveMoneyEntityManagerFactory",
            transactionManagerRef = "receiveMoneyTransactionManager",
            basePackages = {
            "com.abc.sam.money.repository", "com.abc.sam.money.config" })
    public class ReceiveMoneyDBConfig {

        @Primary
        @Bean(name = "receiveMoneyDataSourceProperties")
        @ConfigurationProperties("spring.datasource")
        public DataSourceProperties dataSourceProperties() {
            return new DataSourceProperties();
        }

        @Primary
        @Bean(name = "receiveMoneyDataSource")
        @ConfigurationProperties("spring.datasource.configuration")
        public DataSource dataSource(@Qualifier("receiveMoneyDataSourceProperties") DataSourceProperties receiveMoneyDataSourceProperties) {
            return receiveMoneyDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class)
                    .build();
        }

        @Primary
        @Bean(name = "receiveMoneyEntityManagerFactory")
        public LocalContainerEntityManagerFactoryBean entityManagerFactory(
                EntityManagerFactoryBuilder builder, @Qualifier("receiveMoneyDataSource") DataSource db1DataSource) {
            return builder
                    .dataSource(db1DataSource)
                    .packages("com.abc.sam.money.model")
                    .persistenceUnit("receiveMoney")
                    .build();
        }

        @Primary
        @Bean(name = "receiveMoneyTransactionManager")
        public PlatformTransactionManager transactionManager(
                @Qualifier("receiveMoneyEntityManagerFactory") EntityManagerFactory receiveMoneyEntityManagerFactory) {
            return new JpaTransactionManager(receiveMoneyEntityManagerFactory);
        }

    }```


1 Ответ

0 голосов
/ 04 февраля 2020

Проверьте свои модели данных или таблицы, есть ли имя поле?

Следуйте приведенным ниже стратегиям

Разное Hibernate Naming Strategy

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...