title: Spring Data JPA Multiple Data Sources
body: <p>I have been following this link trying to configure two or more data sources.</p>
  
  <p><a href="https://www.ccampo.me/java/spring/2016/02/13/multi-datasource-spring-boot.html" rel="nofollow noreferrer">https://www.ccampo.me/java/spring/2016/02/13/multi-datasource-spring-boot.html</a></p>
  
  <p>It explains how to define two data sources, But did not explains how to actually use them while querying.</p>
  
  <p>I have created configuration class &amp; added prop in application.prop file. But how to define them in repo function/service function?</p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>public class EmpController {
    @RequestMapping("/abcd")
    public List&lt;Employee&gt; findAll() { return empService.findAll(); }
  }
  </code></pre>
  
  <p><strong>Service</strong></p>
  
  <pre><code>@Service
  public class EmpService {
      @Autowired
      private EmpRepository empRepo;
  
      public List&lt;Employee&gt; findAll() { return empRepo.findAll(); }
  }
  </code></pre>
  
  <p><strong>Repo</strong></p>
  
  <pre><code>public interface EmpRepository extends JpaRepository&lt;Employee, Long&gt; {}
  </code></pre>
  
  <p><strong>Configuration</strong></p>
  
  <pre><code>@Configuration
  public class DataSourceConfiguration {
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    public DataSource numberMasterDataSource() {
      return DataSourceBuilder.create().build();
    }
  
    @Bean
    @ConfigurationProperties(prefix = "datasource.secondary")
    public DataSource provisioningDataSource() {
      return DataSourceBuilder.create().build();
    }
  }
  </code></pre>
  
  <p><strong>application.properties</strong></p>
  
  <pre><code># Primary DataSource configuration
  datasource.primary.url=jdbc:mysql://127.0.0.1:3306/jpa
  datasource.primary.username=root
  datasource.primary.password=root
  # Any of the other Spring supported properties below...
  
  # Secondary DataSource configuration
  datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/jpa2
  datasource.secondary.username=root
  datasource.secondary.password=root
  </code></pre>
  
  <p>Also I donot want to have separate repositories for different datasources as
  I have different DBs for Read &amp; Write. So all my insert queries will be on one server &amp; read queries on other server. If I create different repo/service for read &amp; write, too much redundant code will be there</p>