A Guide to Multitenancy in Hibernate 5 – Hibernate 5中的多租户指南

最后修改: 2018年 1月 6日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Multitenancy allows multiple clients or tenants use a single resource or, in the context of this article, a single database instance. The purpose is to isolate the information each tenant needs from the shared database.

多租户允许多个客户或租户使用单个资源,或者在本文的上下文中,单个数据库实例。其目的是将每个租户需要的信息从共享数据库中分离出来

In this tutorial, we’ll introduce various approaches to configuring multitenancy in Hibernate 5.

在本教程中,我们将介绍在Hibernate 5中配置多租户的各种方法

2. Maven Dependencies

2.Maven的依赖性

We’ll need to include the hibernate-core dependency in the pom.xml file:

我们需要在pom.xml文件中包括hibernate-core依赖

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.2.12.Final</version>
</dependency>

For testing, we’ll use an H2 in-memory database, so let’s also add this dependency to the pom.xml file:

在测试中,我们将使用H2内存数据库,因此我们也将这个依赖性添加到pom.xml文件中。

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.196</version>
</dependency>

3. Understanding Multitenancy in Hibernate

3.了解Hibernate中的多租户

As mentioned in the official Hibernate User Guide, there are three approaches to multitenancy in Hibernate:

正如官方Hibernate用户指南中提到的,Hibernate中的多租户有三种方法。

  • Separate Schema – one schema per tenant in the same physical database instance
  • Separate Database – one separate physical database instance per tenant
  • Partitioned (Discriminator) Data – the data for each tenant is partitioned by a discriminator value

The Partitioned (Discriminator) Data approach isn’t yet supported by Hibernate. Follow up on this JIRA issue for future progress.

Hibernate 尚不支持分区(Discriminator)数据方法。跟进这个JIRA问题,了解未来的进展。

As usual, Hibernate abstracts the complexity around the implementation of each approach.

像往常一样,Hibernate围绕每种方法的实现抽象出了复杂的内容。

All we need is to provide an implementation of these two interfaces:

我们所需要的是提供这两个接口的实现

Let’s see more in detail each concept before going through the database and schema approaches examples.

在通过数据库和模式方法的例子之前,让我们更详细地看看每个概念。

3.1. MultiTenantConnectionProvider

3.1. MultiTenantConnectionProvider

Basically, this interface provides a database connection for a concrete tenant identifier.

基本上,这个接口为一个具体的租户标识符提供了一个数据库连接。

Let’s see its two main methods:

让我们看看它的两个主要方法。

interface MultiTenantConnectionProvider extends Service, Wrapped {
    Connection getAnyConnection() throws SQLException;

    Connection getConnection(String tenantIdentifier) throws SQLException;
     // ...
}

If Hibernate cannot resolve the tenant identifier to use, it will use the method getAnyConnection to get a connection. Otherwise, it will use the method getConnection.

如果Hibernate不能解决要使用的租户标识符,它将使用方法getAnyConnection来获得一个连接。否则,它将使用方法getConnection

Hibernate provides two implementations of this interface depending on how we define the database connections:

Hibernate提供了该接口的两种实现,这取决于我们如何定义数据库连接:

  • Using DataSource interface from Java – we would use the DataSourceBasedMultiTenantConnectionProviderImpl implementation
  • Using the ConnectionProvider interface from Hibernate – we would use the AbstractMultiTenantConnectionProvider implementation

3.2. CurrentTenantIdentifierResolver

3.2. CurrentTenantIdentifierResolver

There are many possible ways to resolve a tenant identifier. For example, our implementation could use one tenant identifier defined in a configuration file.

多种可能的方法来解决租户标识符。例如,我们的实现可以使用配置文件中定义的一个租户标识符。

Another way could be to use the tenant identifier from a path parameter.

另一种方法是使用路径参数中的租户标识符。

Let’s see this interface:

让我们看看这个界面。

public interface CurrentTenantIdentifierResolver {

    String resolveCurrentTenantIdentifier();

    boolean validateExistingCurrentSessions();
}

Hibernate calls the method resolveCurrentTenantIdentifier to get the tenant identifier. If we want Hibernate to validate all the existing sessions belong to the same tenant identifier, the method validateExistingCurrentSessions should return true.

Hibernate调用方法resolveCurrentTenantIdentifier来获取租户标识符。如果我们想让Hibernate验证所有的现有会话属于同一个租户标识符,那么方法validateExistingCurrentSessions应该返回true。

4. Schema Approach

4.模式化的方法

In this strategy, we’ll use different schemas or users in the same physical database instance. This approach should be used when we need the best performance for our application and can sacrifice special database features such as backup per tenant.

在这个策略中,我们将在同一个物理数据库实例中使用不同的模式或用户。当我们需要为我们的应用程序提供最佳性能,并且可以牺牲特殊的数据库功能(如每租户的备份)时,应该使用这种方法。

Also, we’ll mock the CurrentTenantIdentifierResolver interface to provide one tenant identifier as our choice during the test:

另外,我们将模拟CurrentTenantIdentifierResolver接口,在测试中提供一个租户标识符作为我们的选择。

public abstract class MultitenancyIntegrationTest {

    @Mock
    private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;

    private SessionFactory sessionFactory;

    @Before
    public void setup() throws IOException {
        MockitoAnnotations.initMocks(this);

        when(currentTenantIdentifierResolver.validateExistingCurrentSessions())
          .thenReturn(false);

        Properties properties = getHibernateProperties();
        properties.put(
          AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, 
          currentTenantIdentifierResolver);

        sessionFactory = buildSessionFactory(properties);

        initTenant(TenantIdNames.MYDB1);
        initTenant(TenantIdNames.MYDB2);
    }

    protected void initTenant(String tenantId) {
        when(currentTenantIdentifierResolver
         .resolveCurrentTenantIdentifier())
           .thenReturn(tenantId);
        createCarTable();
    }
}

Our implementation of the MultiTenantConnectionProvider interface will set the schema to use every time a connection is requested:

我们对Multi-TenantConnectionProvider接口的实现将设置每次请求连接时要使用的模式

class SchemaMultiTenantConnectionProvider
  extends AbstractMultiTenantConnectionProvider {

    private ConnectionProvider connectionProvider;

    public SchemaMultiTenantConnectionProvider() throws IOException {
        this.connectionProvider = initConnectionProvider();
    }

    @Override
    protected ConnectionProvider getAnyConnectionProvider() {
        return connectionProvider;
    }

    @Override
    protected ConnectionProvider selectConnectionProvider(
      String tenantIdentifier) {
 
        return connectionProvider;
    }

    @Override
    public Connection getConnection(String tenantIdentifier)
      throws SQLException {
 
        Connection connection = super.getConnection(tenantIdentifier);
        connection.createStatement()
          .execute(String.format("SET SCHEMA %s;", tenantIdentifier));
        return connection;
    }

    private ConnectionProvider initConnectionProvider() throws IOException {
        Properties properties = new Properties();
        properties.load(getClass()
          .getResourceAsStream("/hibernate.properties"));

        DriverManagerConnectionProviderImpl connectionProvider 
          = new DriverManagerConnectionProviderImpl();
        connectionProvider.configure(properties);
        return connectionProvider;
    }
}

So, we’ll use one in-memory H2 database with two schemas – one per each tenant.

因此,我们将使用一个具有两个模式的内存H2数据库–每一个租户一个。

Let’s configure the hibernate.properties to use the schema multitenancy mode and our implementation of the MultiTenantConnectionProvider interface:

让我们配置hibernate.properties,以使用模式多租户模式和我们对MultiTenantConnectionProvider接口的实现

hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;\
  INIT=CREATE SCHEMA IF NOT EXISTS MYDB1\\;CREATE SCHEMA IF NOT EXISTS MYDB2\\;
hibernate.multiTenancy=SCHEMA
hibernate.multi_tenant_connection_provider=\
  com.baeldung.hibernate.multitenancy.schema.SchemaMultiTenantConnectionProvider

For the purposes of our test, we’ve configured the hibernate.connection.url property to create two schemas. This shouldn’t be necessary for a real application since the schemas should be already in place.

为了测试的目的,我们配置了hibernate.connection.url属性来创建两个模式。对于真正的应用来说,这应该是没有必要的,因为模式应该已经到位了。

For our test, we’ll add one Car entry in the tenant myDb1. We’ll verify this entry was stored in our database and that it’s not in the tenant myDb2:

对于我们的测试,我们将在租户myDb1中添加一个Car条目。我们将验证这个条目是否存储在我们的数据库中,并且它不在租户myDb2中。

@Test
void whenAddingEntries_thenOnlyAddedToConcreteDatabase() {
    whenCurrentTenantIs(TenantIdNames.MYDB1);
    whenAddCar("myCar");
    thenCarFound("myCar");
    whenCurrentTenantIs(TenantIdNames.MYDB2);
    thenCarNotFound("myCar");
}

As we can see in the test, we change the tenant when calling to the whenCurrentTenantIs method.

正如我们在测试中看到的,我们在调用whenCurrentTenantIs方法时改变了租户。

5. Database Approach

5.数据库方法

The Database multi-tenancy approach uses different physical database instances per tenant. Since each tenant is fully isolated, we should choose this strategy when we need special database features like backup per tenant more than we need the best performance.

数据库多租户方法使用每个租户不同的物理数据库实例。由于每个租户是完全隔离的,当我们需要每个租户的备份等特殊数据库功能而不是需要最佳性能时,我们应该选择这种策略。

For the Database approach, we’ll use the same MultitenancyIntegrationTest class and the CurrentTenantIdentifierResolver interface as above.

对于数据库方法,我们将使用相同的MultitenancyIntegrationTest类和CurrentTenantIdentifierResolver接口,如上所述。

For the MultiTenantConnectionProvider interface, we’ll use a Map collection to get a ConnectionProvider per tenant identifier:

对于Multi-TenantConnectionProvider接口,我们将使用一个Map集合来获取每个租户标识符的ConnectionProvider

class MapMultiTenantConnectionProvider
  extends AbstractMultiTenantConnectionProvider {

    private Map<String, ConnectionProvider> connectionProviderMap
     = new HashMap<>();

    public MapMultiTenantConnectionProvider() throws IOException {
        initConnectionProviderForTenant(TenantIdNames.MYDB1);
        initConnectionProviderForTenant(TenantIdNames.MYDB2);
    }

    @Override
    protected ConnectionProvider getAnyConnectionProvider() {
        return connectionProviderMap.values()
          .iterator()
          .next();
    }

    @Override
    protected ConnectionProvider selectConnectionProvider(
      String tenantIdentifier) {
 
        return connectionProviderMap.get(tenantIdentifier);
    }

    private void initConnectionProviderForTenant(String tenantId)
     throws IOException {
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream(
          String.format("/hibernate-database-%s.properties", tenantId)));
        DriverManagerConnectionProviderImpl connectionProvider 
          = new DriverManagerConnectionProviderImpl();
        connectionProvider.configure(properties);
        this.connectionProviderMap.put(tenantId, connectionProvider);
    }
}

Each ConnectionProvider is populated via the configuration file hibernate-database-<tenant identifier>.properties, which has all the connection details:

每个ConnectionProvider都是通过配置文件hibernate-datab-<tenant identifier>.properties来填充的,该文件有所有连接的细节。

hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:<Tenant Identifier>;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect

Finally, let’s update the hibernate.properties again to use the database multitenancy mode and our implementation of the MultiTenantConnectionProvider interface:

最后,让我们再次更新hibernate.properties,以使用数据库多租户模式和我们对MultiTenantConnectionProvider接口的实现。

hibernate.multiTenancy=DATABASE
hibernate.multi_tenant_connection_provider=\
  com.baeldung.hibernate.multitenancy.database.MapMultiTenantConnectionProvider

If we run the exact same test as in the schema approach, the test passes again.

如果我们运行与模式方法中完全相同的测试,测试又通过了。

6. Conclusion

6.结论

This article covers Hibernate 5 support for multitenancy using the separate database and separate schema approaches. We provide very simplistic implementations and examples to probe the differences between these two strategies.

本文介绍了Hibernate 5对使用独立数据库和独立模式方法的多租户支持。我们提供了非常简单的实现和例子来探究这两种策略之间的区别。

The full code samples used in this article are available on our GitHub project.

本文中使用的完整代码样本可在我们的GitHub项目上获得。