简体   繁体   中英

How can I configure JPA repositories for different DataSources in SpringBoot?

I use spring boot app. I select data from DB by JDBC DataSource and Repositories. Some query by JDBS and some queries by Repositories. My DB configure RAC and has 2 instance. I connect to db by 129.0.0.2 but this URL balanced between 129.0.0.3(1 instance) and 129.0.0.4(2instance) . All queries execute with 129.0.0.2 but some queries I need to execute only on one instance. I created 3 datasources:

@Bean(name = "primary")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "second")
    @ConfigurationProperties(prefix = "spring.secondDatasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "three")
    @ConfigurationProperties(prefix = "spring.threeDatasource")
    public DataSource threeDataSource() {
        return DataSourceBuilder.create().build();
    }

And configure them in application.properties. Then I can write

@Qualifier("primary")DataSource dataSource

or

@Qualifier("second")DataSource dataSource

But what DataSource will use when I execute repositories query?

Create two configurations classes like this:

@Configuration
@EnableJpaRepositories(basePackages = "your.package.repositories.datasource1", 
   entityManagerFactoryRef = entityManagerFactory1)
class DataSource1Configuration {

  @Bean
  public EntityManagerFactory entityManagerFactory1(@Qualifier("primary") DataSource primary) {
    // … create entity manager factory based on primary source
  }
}

Second configuration class would be obviously similar but tailored to use secondary datasource

BTW, since Java 8, it may also be possible to have two annotations of type (two @EnableJpaRepositories in this case) on same class. So it may also work with one configuration class, but two @EnableJpaRepositories annotations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM