A Guide to Multitenancy in Hibernate 5

I just announced the new Spring 5 modules in REST With Spring:

1. Introduction

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

4. Schema Approach

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:

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.

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:

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

5. Database Approach

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.

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

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

6. Conclusion

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.

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