I am working with Spring Boot Microservice project, in this I need to connect to multiple database with same structure based on countries.
What I have done :
-
I have created three configurations in application.properties file.
-
Created three configuration classes to connect with three databases.
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = “abbPhEntityManagerFactory”, basePackages = {
“com.abb.admin.outletph” }
)
public class AbbDbPhConfig {@Bean(name = "abbphdatasource") @ConfigurationProperties(prefix = "spring.abb.ph.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "abbPhEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder, @Qualifier("abbphdatasource") DataSource dataSource) { Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", "none"); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); return builder.dataSource(dataSource).properties(properties).packages("com.abb.admin.outletph") .persistenceUnit("ABBOutletPhMaster").build(); } @Bean(name = "abbPhTransactionManager") public PlatformTransactionManager transactionManager( @Qualifier("abbPhEntityManagerFactory") EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); }
}
-
Created Entities and Repositories to access the data.
To connect with multiple databases I need to make many changes in already existing code, though I know that the structure like : table name, table columns will be same in all databases.
Can’t I use same entities and repositories as DB structure is same, just I need to GET/PUT data in different structure without lots of code changes of different entity and repo classes?
If Yes then how can I achieve this?