I am trying to write a DB sync utility with Spring JPA, where in I have a Source DB and Target DB, having same schema. How do I reuse the Entity objects, Repositories? Currently I am running into issue with a repository bean not being able to be instantiated as it is already associated with first (Source) datasource.
I believe , @Profile cannot be used here , as the Source and Target beans have to co-exist.
Appreciate your thoughts.
CodePudding user response:
It is possible to create several data sources with Spring.
@Configuration
public class JpaConfig {
@Bean(name = "source")
public DataSource h2DataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
dataSourceBuilder.username("sa");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
@Bean(name = "target")
@Primary
public DataSource mySqlDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url("jdbc:mysql://localhost/testdb");
dataSourceBuilder.username("dbuser");
dataSourceBuilder.password("dbpass");
return dataSourceBuilder.build();
}
}
Then, you can get the datasources from the Dependency Injection. You can name them source
and target
so you can keep track of them.
@Qualifier("source")
DataSource source;
@Qualifier("target")
DataSource target;
CodePudding user response:
Here's the solution to your issue with some theoretical background to make understanding easier. Comes with a working example on Github.
I suggest you clone the repo, get it to run and work and then copy the necessary pieces of the code.