Is this possible to do?
I have only found sources where they create multiple repositories and multiple Entity classes to perform this. However, I was not able to find any sources showing that you can have 1 Repository class hit different databases.
Basically, I have a DAO class that has read & write methods. I have a Spring Data repository configured for it, and I am trying to set it up so the Read classes hit the Replica DB whereas the Write classes hit the Main DB.
So far, I have been trying by defining two different SpringDataConfig classes for each DB. Like so:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = { "repo" },
entityManagerFactoryRef = "Write",
transactionManagerRef = "JpaTxnManager_Write")
public class RepositoryConfigSpringDataDbWrite {
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = { "repo" },
entityManagerFactoryRef = "Read",
transactionManagerRef = "JpaTxnManager_Read")
public class RepositoryConfigSpringDataDbRead {
}
Let's call the SpringDataRepository class as EntityRepo. Now, from the DAO class, I am trying to use the @Transactional
annotation to point the specific methods to the specific databases, like so:
@Transactional(transactionManager="JpaTxnManager_Read")
public List<Entity> getAllEntitiesById(String id) {
return entityRepo.findById(id);
}
Some other method that would call Write would be:
@Transactional(transactionManager="JpaTxnManager_Write")
public List<Entity> getAllEntitiesById(Entity entity) {
return entityRepo.save(entity);
}
Any idea if this is possible?