Reputation: 2882
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?
Upvotes: 3
Views: 2295
Reputation: 24561
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.
Upvotes: 1