Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot JPA set custom datasource

I have 2 datasources defined-

#datasource jndi setup
database.datasources[1].jndi-name=jdbc/yyyy
database.datasources[1].username=yyyy
database.datasources[1].password=yyyyy
database.datasources[1].url=jdbc:oracle:thin:@localhost:2222:webtst
database.datasources[1].driverClassName=oracle.jdbc.OracleDriver
database.datasources[1].factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.datasources[1].initialSize=1
database.datasources[1].maxActive=5

database.datasources[0].jndi-name=jdbc/xxx
database.datasources[0].username=xxx
database.datasources[0].password=xxxx
database.datasources[0].url=jdbc:oracle:thin:@localhost:2222:webtst
database.datasources[0].driverClassName=oracle.jdbc.OracleDriver
database.datasources[0].factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.datasources[0].initialSize=1
database.datasources[0].maxActive=15 

And 2 matching JPA repositories, how can I set one of them to use different ds(not the primary one) after I defined one of them to be @Primary :

@Bean
@Primary
DataSource dataSource() throws SQLException {
    OracleDataSource dataSource = new OracleDataSource();
    dataSource.setUser(xusername);
    dataSource.setPassword(xpassword);
    dataSource.setURL(xurl);

    dataSource.setImplicitCachingEnabled(true);
    dataSource.setFastConnectionFailoverEnabled(true);
    return dataSource;
}



@Bean
DataSource propsDataSource() throws SQLException {
    OracleDataSource propsDataSource = new OracleDataSource();
    //propsDataSource.setDataSourceName(secJNDIName);
    propsDataSource.setUser(yUserName);
    propsDataSource.setPassword(ypropsPassword);
    propsDataSource.setURL(upropsUrl);
    propsDataSource.setImplicitCachingEnabled(true);
    propsDataSource.setFastConnectionFailoverEnabled(true);
    return propsDataSource;
}

And a simple JpaRepository that I want it to use seconday data-source:

public interface AttributesRepo extends JpaRepository<PRODUCTATTRIBUTE, PRODUCTATTRIBUTE_KEY> {

}
like image 465
Itsik Mauyhas Avatar asked Aug 26 '26 03:08

Itsik Mauyhas


1 Answers

You need to:

  • define two DataSource
  • mark one of them as @Primary (like you did)
  • define two LocalContainerEntityManagerFactoryBean em1 and em2 each using a different DataSource
  • define two TransactionManagers
  • put all the repositories which should use the first DataSource into package pkg1 and the other repositories into package pkg2
  • define a @Configuration class with @EnableJpaRepositories with basePackages = "pkg1" and entityManagerFactoryRef = "em1"
  • add the second @Configuration class for pkg2 and em2

It is described in the Spring Boot documentation - 8.2 Configure Two DataSources.

like image 114
Adam Siemion Avatar answered Aug 27 '26 18:08

Adam Siemion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!