简体   繁体   中英

JPA config with multiple repository implementation for a single repository

I have a scenario where i need to have 2 different implementation of a single repository (only one repository will be active at a time) based on Database from which that repository implementation is getting the data.

Example: GroupRepository extends CrudRepository <String,Group>{} GroupSybaseRepository extends GroupRepository <String,Group>{} GroupDB2Repository extends GroupRepository <String,Group>{}

The solution that i am planning to have these repository implementation in different packages and using includeFilters/excludeFilters with

Any other better approach?

You can use spring profiles.

Have two profile names db2 and sysbase and Mark your repository accordingly with @Profile annotation.

While running the application specify which profile you want to be active using spring.profiles.active system property.

You can find an example here

You can use two Repositories in the separate location, but you can achieve this by multiple ways( may be :-) )

But One could be:-

Using different Transaction Managers Like Below:-

@Repository()
@Transactional(value = "syBaseTransactionManager")
public interface GroupSybaseRepository extends GroupRepository <String,Group>{

}

@Repository()
@Transactional(value = "db2TransactionManager")
public interface GroupDB2Repository extends GroupRepository <String,Group>{

}

Now here you will be having multiple Transaction Managers in your context obviously. Thanks.

And you can have Conditional repositories also for the same. May be different configuration( classes marked with @Configuration marked with @Conditional based on some environment variable) files for both packages and transaction Manager Beans and other related beans also

I used a combination of include/exclude filters the only bad part was that i have to comment/un-comment the specific filter definition when need to switch between repositories implementation. Something like below

<context:component-scan base-package="com.concretepage">
 <context:include-filter type="regex" expression="com.concretepage.*.*Util"/>
 <context:exclude-filter type="assignable" expression="com.concretepage.service.IUserService"/>             
</context:component-scan>  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM