title: Multiple datasources in Spring Boot Repository Annotated Interface
body: <p>My application is based on Spring Boot, Hibernate, MySQL using Spring Data JPA to stitch them. </p>
  
  <p>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.</p>
  
  <p><a href="https://stackoverflow.com/questions/26308035/spring-boot-spring-data-jpa-with-multiple-datasources">Spring Boot, Spring Data JPA with multiple DataSources</a></p>
  
  <p><a href="https://scattercode.co.uk/2016/01/05/multiple-databases-with-spring-boot-and-spring-data-jpa/" rel="nofollow noreferrer">https://scattercode.co.uk/2016/01/05/multiple-databases-with-spring-boot-and-spring-data-jpa/</a></p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>public interface CustomerRepository extends JpaRepository&lt;Customer, Integer&gt;, MyCustomCustomerRepository{
  }
  
  public class MyCustomCustomerRepositoryImpl implements MyCustomCustomerRepository {
  
          @PersistenceContext(unitName = "entityManagerFactoryTwo")
          EntityManager entityManager;
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>NOTE: Entities are same in both databases so giving separate packages for entity scanning and similar solutions might not work.</p>