Jes*_*per 3 java mysql spring hibernate multi-tenant
我正在将 spring + hibernate + mysql 设置更改为多租户。首先,我的 中有以下内容application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
Run Code Online (Sandbox Code Playgroud)
我不确定test引入多租户后是否应该让它连接到此处的特定模式 ( )?这对我来说没有意义,因为如果没有提供租户,它应该使用默认架构,否则连接到与租户关联的架构。但是,如果我删除它,我会收到一条错误消息,指出未提供数据库。
其次,多租户部分似乎不起作用。我所有的查询都是在test架构中进行的。我已经实施了以下措施MultiTenantConnectionProvider:
@Component
public class TenantConnectionProvider implements MultiTenantConnectionProvider {
private Datasource datasource;
public TenantConnectionProvider(DataSource datasource) {
this.datasource = datasource;
}
...
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
logger.info("Get connection for tenant {}", tenantIdentifier);
final Connection connection = getAnyConnection();
connection.setSchema(tenantIdentifier);
return connection;
}
@Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
logger.info("Release connection for tenant {}", tenantIdentifier);
connection.setSchema(DEFAULT_TENANT);
releaseAnyConnection(connection);
}
}
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误,并且当我进行查询时,它会正确打印与我的其他模式之一的名称相匹配的Get connection for tenant正确内容。tenantIdentifier尽管如此,它还是会查询test架构。我缺少什么?谢谢!
编辑:
好像connection.setSchema(tenantIdentifier)没有什么效果。在该方法的描述中,有以下内容:If the driver does not support schemas, it will silently ignore this request。所以我猜我的驱动程序不支持它?这种情况该怎么办?
使用connection.createStatement().execute("USE " + tenantIdentifier);而不是connection.setSchema(tenantIdentifier);解决了我的问题。