Skip to content

Latest commit

 

History

History
268 lines (207 loc) · 12.8 KB

File metadata and controls

268 lines (207 loc) · 12.8 KB

Multitenancy

What is multitenancy?

The term multitenancy, in general, is applied to software development to indicate an architecture in which a single running instance of an application simultaneously serves multiple clients (tenants). This is highly common in SaaS solutions. Isolating information (data, customizations, etc.) pertaining to the various tenants is a particular challenge in these systems. This includes the data owned by each tenant stored in the database. It is this last piece, sometimes called multitenant data, that we will focus on.

Multitenant data approaches

There are three main approaches to isolating information in these multitenant systems which go hand-in-hand with different database schema definitions and JDBC setups.

Note

Each multitenancy strategy has pros and cons as well as specific techniques and considerations. Such topics are beyond the scope of this documentation.

Separate database

multitenacy database

Each tenant’s data is kept in a physically separate database instance. JDBC Connections would point specifically to each database so any pooling would be per-tenant. A general application approach, here, would be to define a JDBC Connection pool per-tenant and to select the pool to use based on the tenant identifier associated with the currently logged in user.

Separate schema

multitenacy schema

Each tenant’s data is kept in a distinct database schema on a single database instance. There are two different ways to define JDBC Connections here:

  • Connections could point specifically to each schema as we saw with the Separate database approach. This is an option provided that the driver supports naming the default schema in the connection URL or if the pooling mechanism supports naming a schema to use for its Connections. Using this approach, we would have a distinct JDBC Connection pool per-tenant where the pool to use would be selected based on the "tenant identifier" associated with the currently logged in user.

  • 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.

Partitioned (discriminator) data

multitenacy discriminator

All data is kept in a single database schema. The data for each tenant is partitioned by the use of partition value or discriminator. The complexity of this discriminator might range from a simple column value to a complex SQL formula. Again, this approach would use a single Connection pool to service all tenants. However, in this approach, the application needs to alter each and every SQL statement sent to the database to reference the "tenant identifier" discriminator.

Multitenancy in Hibernate

Using Hibernate with multitenant data comes down to both an API and then integration piece(s). As usual, Hibernate strives to keep the API simple and isolated from any underlying integration complexities. The API is really just defined by passing the tenant identifier as part of opening any session.

Example 1. Specifying tenant identifier from SessionFactory
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java[role=include]

@TenantId

For the partitioned data approach, each entity representing partitioned data must declare a field annotated @TenantId.

Example 2. A @TenantId usage example
@Entity
public class Account {

    @Id @GeneratedValue Long id;

    @TenantId String tenantId;

    ...
}

The @TenantId field is automatically populated by Hibernate when an instance is made persistent.

MultiTenantConnectionProvider

When using either the separate database or separate schema approach, Hibernate needs to be able to obtain connections in a tenant-specific manner.

That is the role of the MultiTenantConnectionProvider contract. Application developers will need to provide an implementation of this contract.

Most of its methods are extremely self-explanatory. The only ones which might not be are getAnyConnection and releaseAnyConnection. It is important to note also that these methods do not accept the tenant identifier. Hibernate uses these methods during startup to perform various configuration, mainly via the java.sql.DatabaseMetaData object.

The MultiTenantConnectionProvider to use can be specified in a number of ways:

  • Use the hibernate.multi_tenant_connection_provider setting. It could name a MultiTenantConnectionProvider instance, a MultiTenantConnectionProvider implementation class reference or a MultiTenantConnectionProvider implementation class name.

  • Provided by the configured BeanContainer.

  • Passed directly to the org.hibernate.boot.registry.StandardServiceRegistryBuilder.

  • If none of the above options match, but the settings do specify a hibernate.connection.datasource value, Hibernate will assume it should use the specific DataSourceBasedMultiTenantConnectionProviderImpl implementation which works on a number of pretty reasonable assumptions when running inside of an app server and using one javax.sql.DataSource per tenant. See its Javadocs for more details.

The following example portrays a MultiTenantConnectionProvider implementation that handles multiple ConnectionProviders.

Example 3. A MultiTenantConnectionProvider implementation
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurableMultiTenantConnectionProvider.java[role=include]

The ConfigurableMultiTenantConnectionProvider can be set up as follows:

Example 4. A MultiTenantConnectionProvider usage example
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java[role=include]

When using multitenancy, it’s possible to save an entity with the same identifier across different tenants:

Example 5. An example of saving entities with the same identifier across different tenants
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java[role=include]

CurrentTenantIdentifierResolver

org.hibernate.context.spi.CurrentTenantIdentifierResolver is a contract for Hibernate to be able to resolve what the application considers the current tenant identifier. The implementation to use can be either passed directly to Configuration via its setCurrentTenantIdentifierResolver method, or be specified via the hibernate.tenant_identifier_resolver setting, or be provided by the configured BeanContainer.

There are two situations where CurrentTenantIdentifierResolver is used:

  • The first situation is when the application is using the org.hibernate.context.spi.CurrentSessionContext feature in conjunction with multitenancy. In the case of the current-session feature, Hibernate will need to open a session if it cannot find an existing one in scope. However, when a session is opened in a multitenant environment, the tenant identifier has to be specified. This is where the CurrentTenantIdentifierResolver comes into play; Hibernate will consult the implementation you provide to determine the tenant identifier to use when opening the session. In this case, it is required that a CurrentTenantIdentifierResolver is supplied.

  • The other situation is when you do not want to explicitly specify the tenant identifier all the time. If a CurrentTenantIdentifierResolver has been specified, Hibernate will use it to determine the default tenant identifier to use when opening the session.

Additionally, if the CurrentTenantIdentifierResolver implementation returns true for its validateExistingCurrentSessions method, Hibernate will make sure any existing sessions that are found in scope have a matching tenant identifier. This capability is only pertinent when the CurrentTenantIdentifierResolver is used in current-session settings.

Caching

Multitenancy support in Hibernate works seamlessly with the Hibernate second level cache. The key used to cache data encodes the tenant identifier.

Note

Currently, schema export will not really work with multitenancy.

Multitenancy Hibernate Session configuration

When using multitenancy, you might want to configure each tenant-specific Session differently. For instance, each tenant could specify a different time zone configuration.

Example 6. Registering the tenant-specific time zone information
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]

The registerConnectionProvider method is used to define the tenant-specific context.

Example 7. The registerConnectionProvider method used for defining the tenant-specific context
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]

For our example, the tenant-specific context is held in the connectionProviderMap and timeZoneTenantMap.

link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]

Now, when building the Hibernate Session, aside from passing the tenant identifier, we could also configure the Session to use the tenant-specific time zone.

Example 8. The Hibernate Session can be configured using the tenant-specific context
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]

So, if we set the useTenantTimeZone parameter to true, Hibernate will persist the Timestamp properties using the tenant-specific time zone. As you can see in the following example, the Timestamp is successfully retrieved even if the currently running JVM uses a different time zone.

Example 9. The useTenantTimeZone allows you to persist a Timestamp in the provided time zone
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]

However, behind the scenes, we can see that Hibernate has saved the created_on property in the tenant-specific time zone. The following example shows you that the Timestamp was saved in the UTC time zone, hence the offset displayed in the test output.

Example 10. With the useTenantTimeZone property set to false, the Timestamp is fetched in the tenant-specific time zone
link:../../../../../../../hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java[role=include]
link:extras/multitenacy-hibernate-not-applying-timezone-configuration-example.sql[role=include]

Notice that for the Eastern European Time time zone, the time zone offset was 2 hours when the test was executed.