如何在Spring Boot中以默认模式以编程方式配置Oracle DataSource?
@Bean
public DataSource getDataSource() throws SQLException {
OracleDataSource d = new OracleDataSource();
d.setURL(Secrets.get("DB_URL"));
d.setUser(Secrets.get("DB_USER"));
d.setPassword(Secrets.get("DB_PASS"));
// d.setSchema(System.getenv("DB_SCHEMA")); ???
return d;
}
答案 0 :(得分:2)
您无法在OracleDataSource
或使用连接URL中更改架构,需要执行
ALTER SESSION SET CURRENT_SCHEMA=targetschema;
声明,如this answer中所述。根据{{3}},初始模式没有驱动程序属性。
答案 1 :(得分:1)
尝试将sql执行添加到数据源创建方法中
@Bean
public DataSource getDataSource() throws SQLException {
OracleDataSource d = new OracleDataSource();
d.setURL(Secrets.get("DB_URL"));
d.setUser(Secrets.get("DB_USER"));
d.setPassword(Secrets.get("DB_PASS"));
Resource initSchema = new ClassPathResource("scripts/schema-alter.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema);
DatabasePopulatorUtils.execute(databasePopulator, dataSource);
return d;
}
在scripts / schema-alter.sql中将是此代码
ALTER SESSION SET CURRENT_SCHEMA=targetschema;
答案 2 :(得分:1)
完整示例:
@Bean
public DataSource getDataSource() throws SQLException {
OracleDataSource oracleDs = new OracleDataSource();
oracleDs.setURL(Secrets.get("DB_URL"));
oracleDs.setUser(Secrets.get("DB_USER"));
oracleDs.setPassword(Secrets.get("DB_PASS"));
// other Oracle related settings...
HikariDataSource hikariDs = new HikariDataSource();
hikariDs.setDataSource(oracleDs);
hikariDs.setConnectionInitSql("ALTER SESSION SET CURRENT_SCHEMA = MY_SCHEMA");
return hikariDs;
}
答案 3 :(得分:1)
在Spring Boot 2中,可以在application.properties文件中使用以下属性设置所需的模式:
spring.datasource.hikari.connection-init-sql=ALTER SESSION SET CURRENT_SCHEMA = MY_SCHEMA
HikariCP是Spring Boot 2中的默认连接池。要在日志文件中查看所有HikariCP设置(包括“ connectionInitSql”),请在application.properties中添加以下内容:
logging.level.com.zaxxer.hikari=DEBUG