I have a Spring Boot project with one entity and one repository associated to this entity. In the repository there is one method with a custom query and in the project contr
Create 2 config files with different datasource and these 2 config files will have different specifications for 2 different jpa repository class.but can have same domain class.
step1> In your properties file have 2 datasource details.
spring.datasource.url=jdbc:postgresql://localhost:5432/DB2017_test
spring.datasource.username=xxx
spring.datasource.password=xxx
# DB2018 DB - ""
spring.datasource2.url=jdbc:postgresql://localhost:5432/DB2018_test
spring.datasource2.username=xxx
spring.datasource2.password=xxx
step2>Then create config file for first dataSource
package com.package1;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.package1.repo" }
)
public class DB2017Config {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.domain")
.persistenceUnit("foo")
.build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
step3> Similary create another config file for other dataSource,
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.package2.repo" }
And change prefix
@ConfigurationProperties(prefix = "spring.datasource2")
Now you will have 2 similar RequestRepository1 and RequestRepository2 in package1 and package2 respectiverly as mentioned above (basePackages = { "com.package1.repo" }).
step4>All set autowire 2 different repo .
@Autowired
private final RequestRepository1 repo1;
@Autowired
private final RequestRepository2 repo2;
Then use them.
List listAdesioni = repo1.findByCodiceFiscale(codicefiscale);
List listAdesioni = repo2.findByCodiceFiscale(codicefiscale);