多租户Hibernate SCHEMA方法,切换架构使用mysql但有问题

时间:2017-04-11 09:12:22

标签: java mysql hibernate multi-tenant

我已经使用mysqlhibernate实现了多租户,但我怀疑它是否适用于现实世界。

根据hibernate文档中的以下引用,它应该是可能的:

Connections could point to the database itself (using some default schema) but the Connections would be altered using the SQL SET SCHEMA (or similar) command. Using this approach, we would have a single JDBC Connection pool for use to service all tenants, but before using the Connection it would be altered to reference the schema named by the “tenant identifier” associated with the currently logged in user.

这是我从上面开始的链接。

Multitenancy in hibernate

所以我覆盖MultiTenantConnectionProvider,如下所示

@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
    Connection tenantSpecificConnection = dataSource.getConnection();
    if (!StringUtils.isEmpty(tenantIdentifier)) {
        Statement statement = tenantSpecificConnection.createStatement();
        statement.executeQuery("use " + tenantIdentifier);
        statement.close();
        tenantSpecificConnection.setSchema(tenantIdentifier);
    } else {
        tenantSpecificConnection.setSchema(Constants.DEFAULT);
    }
    return tenantSpecificConnection;
}

这是非常基本的迭代,第一个,我只能切换数据库。但有了这个,我也有疑问。这会在现实世界中发挥作用吗?我认为多个用户在使用时会造成麻烦吗?根据hibernate文档它不应该,但它看起来可能会导致问题。有没有人试过这个,请在​​这个上需要帮助。

0 个答案:

没有答案