Home > Mobile >  Spring data JPA : How to organize repositories and service layer for multiple datasources containing
Spring data JPA : How to organize repositories and service layer for multiple datasources containing

Time:04-01

I have an entity EntityA that is present in multiple datasources, datasourceA and datasourceB. Basically, same table but different content exists in both databases.

How should I organize my spring boot application in this scenario? Currently I have the following :

  • 1 entity class
  • 2 Repositories, one for each datasource. I have a config file that indicate the datasource that a repository should use.
  • 1 service class which, based on a given argument, queries one of the repositories.

The problem with this is that, in my real program, I have 6 entities that are all shared among 6 datasources, which leads me to have 32 repositories, one for each entity and for each datasource. Also my code for choosing the right repository to use in the service class gets quite long.

Is this the best way to approach the problem or is there a way to better organize this / limit the number of repositories needed? Spring boot is using hibernate in my application.

CodePudding user response:

If these duplicate entities will be always updated at same time for each data source then you can maintain only one entity as system wide. Otherwise, you need to create unique entities for each data source. You already stated that you configured datasources for repository management. You can also centralized the usage of repositories by inheritance. Like;

public interface BaseLoadRepository extends CrudRepository<LoadEntity, Long>

public interface DataSource1LoadRepo extends BaseLoadRepository

public interface DataSource2LoadRepo extends BaseLoadRepository

It gives you opportunity to add new method independently for each datasource. This approach also can be used for entites.

  • Related