Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
Himanshu Virmani Avatar asked Sep 01 '16 07:09

Himanshu Virmani


People also ask

How do I add multiple datasources in spring boot?

So, to use multiple data sources, we need to declare multiple beans with different mappings within Spring's application context. The configuration for the data sources must look like this: spring: datasource: todos: url: ... username: ...

How do I add multiple dialects in spring boot?

To connect multiple databases, each database should be configured in its own spring boot configuration file. Multiple data sources should be configured for multiple databases. For spring data classes and spring data JPA repositories, two separate java packages need be created.

Can we have multiple repository in spring boot?

You can only have one repository per entity... however, you can have multiple entities per table; thus, having multiple repositories per table.


1 Answers

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.

like image 64
oborovyk Avatar answered Nov 17 '22 00:11

oborovyk