Himanshu Virmani
Himanshu Virmani

Reputation: 2460

Multiple datasources in Spring Boot Repository Annotated Interface

My application is based on Spring Boot, Hibernate, MySQL using Spring Data JPA to stitch them.

Use case is to use slave db node for doing heavy read operations so as to avoid all traffic being served from master mysql node. One way of achieving this is to have multiple Entity Managers pointing to separate data sources(one to master and other to slave node). This way has been explained quite well in below SO questions and blogs.

Spring Boot, Spring Data JPA with multiple DataSources

https://scattercode.co.uk/2016/01/05/multiple-databases-with-spring-boot-and-spring-data-jpa/

Where I am stuck is to understand if there is a way I can inject different entity managers for different use cases in my Repository Annotated Interface.

The only way I see it can be done is extending repository with a custom implementation which gives uses custom entity manager annotated with relevant persistenceContext like below.

public interface CustomerRepository extends JpaRepository<Customer, Integer>, MyCustomCustomerRepository{
}

public class MyCustomCustomerRepositoryImpl implements MyCustomCustomerRepository {

        @PersistenceContext(unitName = "entityManagerFactoryTwo")
        EntityManager entityManager;
}

I would like to avoid doing this custom implementation. Any help around solving this use case(which I feel should be very common) would be appreciated.

NOTE: Entities are same in both databases so giving separate packages for entity scanning and similar solutions might not work.

Upvotes: 8

Views: 2683

Answers (2)

Himanshu Virmani
Himanshu Virmani

Reputation: 2460

Below is the pull request that shows the diff and how I made it work with most configurations annotation driven instead of xml. It is based on cra6's answer above. i.e. using spring's RoutingDataSource capability.

https://github.com/himanshuvirmani/rest-webservice-sample/pull/1/files

Upvotes: 2

oborovyk
oborovyk

Reputation: 385

Here is a nice sample you can use: dynamic-datasource-routing-with-spring. Inside you can find an AbstractRoutingDatasource + an interceptor for a custom annotation that wires the service method to a required database. However you can just use datasource switch explicitly.

Upvotes: 5

Related Questions