如何通过application.yml为具有多个数据源的Spring Boot应用程序配置JPA存储库模式?

时间:2019-01-11 04:58:49

标签: java spring-boot jpa

我想在yml文件中为anotherDataSource指定架构,而不是在@table批注中指定。但是,如果我从@Table批注中删除该架构,它将无法正常工作。 我不能将spring.jpa.properties.hibernate.default_schema属性用于anotherDataSource,因为它已经包含了主数据源的架构。

application.yml

spring:
  profiles: LOCAL   
  datasource:
    url: jdbc:oracle:thin:@//testhost:8888/ABCDEF
    username: USER1
    password: PWD1    
    driver-class-name: oracle.jdbc.driver.OracleDriver
  anotherDataSource:
    url: jdbc:oracle:thin:@//testhosttwo:1526/GHIJKL
    username: USER2
    password: PWD2
    driver-class-name: oracle.jdbc.driver.OracleDriver
    schema: MNOPQR

AnotherDataSourceConfig.java

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = "com.test.another.repository"
)

@EnableTransactionManagement
public class AnotherDataSourceConfig {
    @Bean(name = "anotherEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean anotherEntityManagerFactory(final EntityManagerFactoryBuilder builder, final @Qualifier("destinationDb") DataSource dataSource) {
        return builder
            .dataSource(dataSource)
            .packages("com.test.another.domain")
            .persistenceUnit("destinationDb")
            .build();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager anotherTransactionManager(@Qualifier("anotherEntityManagerFactory") EntityManagerFactory anotherEntityManagerFactory) {
        return new JpaTransactionManager(anotherEntityManagerFactory);
    }          
}

DBConfig.java

@Configuration
public class DBConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(name= "sourceDb")
    @Primary
    public DataSource sourceDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "destinationDb")
    @ConfigurationProperties(prefix="spring.anotherDataSource")
    public DataSource destinationDataSource(){
        return DataSourceBuilder.create().build();
    }
}

MYTABLE.java

package com.test.another.domain;
@Entity
@Table(name = "MYTABLE", schema = "MNOPQR")
public class MYTABLE {
    ...
}

0 个答案:

没有答案