How to create a single configuration java file with multiple data sources configuration mentioned in the application.properties such that while adding any 'n' number of datasources. It must handle all the datasources automatically with the same configuration file.
Furthermore, all the datasources must use the same JPARepository to query the data. Also, I want to create a list of entity managers to perform specific operations on specfic datasources.
application.properties
site1.url=jdbc:postgresql://localhost:4567/postgres
site1.username=someUsername
site1.password=somePassword
site2.url=jdbc:postgresql://localhost:5433/postgres
site2.username=someUsername
site2.password=somePassword
SiteConfiguration.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "site1EntityManager",
transactionManagerRef = "site1TransactionManager",
basePackages = "com.someProject.repositoryInterface"
)
public class Site1Config extends HikariConfig {
@Autowired
private Environment environment;
@Primary
@Bean(name = "site1EntityManager")
public HikariDataSource mysqlDataSource() {
setJdbcUrl(environment.getProperty("site1.url"));
setUsername(environment.getProperty("site1.username"));
setPassword(environment.getProperty("site1.password"));
return new HikariDataSource(this);
}
@Primary
@Bean(name = "site1EntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(mysqlDataSource())
.packages(ModelClass.class)
.persistenceUnit("site1PU")
.build();
}
@Primary
@Bean(name = "site1TransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("site1EntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
This is the basic example of the single datasource configuration file. I want to make SiteConfiguration as generic class in the form of 'site(Number)' and create a separate datasources, entity managers for each of the cases.
AUTOMATICALLY IT SHOULD FETCH THE NUMBER OF DATASOURCES FROM application.properites AND IT SHOULD CONFIGURE ALL THE DATASOURCES MENTIONED IN PROPERTIES FILE.
Also, every datasource must use the same JPARepository.