【发布时间】:2020-07-30 17:44:09
【问题描述】:
我的项目在 spring-boot-starter-parent - "1.5.9.RELEASE" 上,我正在将它迁移到 spring-boot-starter-parent - "2.3.1.RELEASE"。
这是一个多租户环境应用程序,其中一个数据库将具有多个模式,并根据租户 ID 在模式之间切换执行。
我已经使用 SimpleNativeJdbcExtractor 实现了这种模式切换,但在最新的 Springboot 版本中,NativeJdbcExtractor 不再可用。
现有实现的代码 sn-p:
@Bean
@Scope(
value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
SimpleNativeJdbcExtractor simpleNativeJdbcExtractor = new SimpleNativeJdbcExtractor() {
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
LOGGER.debug("Set schema for getNativeConnection "+Utilities.getTenantId());
con.setSchema(Utilities.getTenantId());
return super.getNativeConnection(con);
}
@Override
public Connection getNativeConnectionFromStatement(Statement stmt) throws SQLException {
LOGGER.debug("Set schema for getNativeConnectionFromStatement "+Utilities.getTenantId());
Connection nativeConnectionFromStatement = super.getNativeConnectionFromStatement(stmt);
nativeConnectionFromStatement.setSchema(Utilities.getTenantId());
return nativeConnectionFromStatement;
}
};
simpleNativeJdbcExtractor.setNativeConnectionNecessaryForNativeStatements(true);
simpleNativeJdbcExtractor.setNativeConnectionNecessaryForNativePreparedStatements(true);
jdbcTemplate.setNativeJdbcExtractor(simpleNativeJdbcExtractor);
return jdbcTemplate;
}
这里的 Utilities.getTenantId()(存储在 ThreadLocal 中的值)将根据 REST 请求给出架构名称。
问题:
- NativeJdbcExtractor 的替代方法是什么,以便可以为 JdbcTemplate 动态更改架构?
- 有没有其他方法,在创建 JdbcTemplate bean 时,我可以根据请求设置架构。
非常感谢任何帮助、代码 sn-p 或解决此问题的指导。
谢谢。
【问题讨论】:
-
* 在 Springboot2 上是否可行? * 我应该摆脱 JdbcTemplate 吗? (需要大量的编码和测试工作)* 我应该停止迁移吗?
标签: java database spring-boot multi-tenant jdbctemplate