簡體   English   中英

在 Spring Boot 中使用默認模式以編程方式配置 OracleDataSource

[英]Configure OracleDataSource programmatically in Spring Boot with a default schema

如何使用默認模式在 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;
}

您不能更改OracleDataSource的架構或使用連接 URL,您需要執行

ALTER SESSION SET CURRENT_SCHEMA=targetschema;

本答案中解釋的聲明。 根據Oracle JDBC 驅動程序識別的連接屬性,初始模式沒有驅動程序屬性。

嘗試將 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;

完整示例:

@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;
}

在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM