【发布时间】:2018-04-01 12:06:49
【问题描述】:
我需要创建一个多租户应用程序,该应用程序能够在我的 java 代码中的模式之间切换(不是基于用户请求)。
我读过文章: https://fizzylogic.nl/2016/01/24/make-your-spring-boot-application-multi-tenant-aware-in-2-steps/ http://www.greggbolinger.com/tenant-per-schema-with-spring-boot/ 当架构在 Rest-request 中传递时,解决方案工作正常。
但是我需要实现以下逻辑:
public void compare(String originalSchema, String secondSchema){
TenantContext.setCurrentTenant(originalSchema);
List<MyObject> originalData = myRepository.findData();
TenantContext.setCurrentTenant(secondSchema);
List<MyObject> migratedData = myRepository.findData();
}
关键是,当我手动设置 TenenantContext 时,连接并没有切换。 MultiTenantConnectionProviderImpl.getConnection 仅在第一次调用我的存储库时被调用。
@Component
public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider {
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement().execute( "ALTER SESSION SET CURRENT_SCHEMA = " + tenantIdentifier );
}
catch ( SQLException e ) {
throw new HibernateException(
"Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]",e);
}
return connection;
}
}
是否可以强制切换会话?
【问题讨论】:
-
是的,这是可能的,但您需要在事务范围之外切换会话。
-
@Andriy Slobodyanyk,我不手动创建交易。我有一项服务,它没有事务注释并调用存储库。交易债券从何而来?
标签: spring hibernate spring-boot spring-data-jpa