Spring boot JPA 设置自定义数据源

Its*_*has 1 java datasource spring-boot

我定义了 2 个数据源-

#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 
Run Code Online (Sandbox Code Playgroud)

和 2 个匹配的 JPA 存储库,在我将其中一个定义为 @Primary 后,如何将其中一个设置为使用不同的 ds(不是主要的):

@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;
}
Run Code Online (Sandbox Code Playgroud)

还有一个简单的 JpaRepository,我希望它使用辅助数据源:

public interface AttributesRepo extends JpaRepository<PRODUCTATTRIBUTE, PRODUCTATTRIBUTE_KEY> {

}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ion 7

你需要:

  • 定义两个 DataSource
  • 将其中一个标记为@Primary(就像你一样)
  • 定义两个LocalContainerEntityManagerFactoryBean em1em2每个使用不同的DataSource
  • 定义两个 TransactionManagers
  • 将所有应该使用第一个的存储库DataSource放入包中pkg1,将其他存储库放入包中pkg2
  • 用和定义一个@Configuration@EnableJpaRepositoriesbasePackages = "pkg1"entityManagerFactoryRef = "em1"
  • 蚂蚁的第二@Configurationpkg2em2

它在Spring Boot 文档 - 84.10 Use Two EntityManagers 中有描述