8

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.

2
  • 1
    Does this sample helps? Commented Sep 1, 2016 at 8:16
  • 1
    Demo you shared has two different entities in different dbs. it becomes easier to avoid conflicts when using two entity managers for such a case. For me Entities remain same whether we use them for master or slave db. Commented Sep 1, 2016 at 16:10

2 Answers 2

5
+50

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Though the sample is doing suff using xml configs and my project is mostly annotation driven, the answer provided gives me good context on how to achieve the functionality. Thanks :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.