![](/img/trans.png)
[英]Using AbstractRoutingDataSource to dynamically change the database schema/catalog
[英]How to dynamically change database/catalog when using Spring JdbcTemplate
考慮一種情況,其中所有客戶端數據都存儲在其自己的數據庫/目錄中,並且所有此類數據庫都存儲在單個RDBMS(客戶端數據)中。 主數據(例如客戶端,......)保存在另一個RDBMS(主數據)中。 我們如何通過JdbcTemplate
動態訪問客戶端數據RDBMS中的特定數據庫?
為客戶端數據RDBMS中的每個數據庫定義DataSource
,然后根據此處的建議動態選擇一個數據DataSource
,因為數據庫是動態創建和銷毀的。
我基本上需要像JDBC的Connection.setCatalog(String catalog)
這樣的東西,但是我沒有在Spring JdbcTemplate
找到類似的東西。
也許你可以換的數據源與DelegatingDataSource
調用setCatalog()
中getConnection()
並使用所包裝的數據源JdbcTemplate
創作:
class MyDelegatingDS extends DelegatingDataSource {
private final String catalogName;
public MyDelegatingDS(final String catalogName, final DataSource dataSource) {
super(dataSource);
this.catalogName = catalogName;
}
@Override
public Connection getConnection() throws SQLException {
final Connection cnx = super.getConnection();
cnx.setCatalog(this.catalogName);
return cnx;
}
// maybe also override the other getConnection();
}
// then use like that: new JdbcTemplate(new MyDelegatingDS("catalogName", dataSource));
您可以從JdbcTemplate
訪問Connection
:
jdbcTemplate.getDataSource().getConnection().setCatalog(catalogName);
您只需確保數據庫驅動程序支持此功能。
jdbcTemplate.getDataSource().getConnection().setSchema(schemaName)
是我使用postgres切換模式所需要的。 推薦給@ m3th0dman讓我走上正軌。 我只是添加這個,以防其他人發現這個答案正在尋找切換架構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.