Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – JPA Buddy – JPA (partner)
announcement - icon

JPA is huge! It covers nearly every aspect of communication between relational databases and the Java application and is deeply integrated into all major frameworks.

If you're using IntelliJ, JPA Buddy is super helpful. The plugin gently guides you through the subtleties of the most popular JPA implementations, visually reminds you of JPA features, generates code that follows best practices, and integrates intelligent inspections to improve your existing persistence code.

More concretely, it provides powerful tooling to generate Spring Data JPA repositories and methods, Flyway Versioned Migrations, Liquibase Differential Changelogs, DDL and SQL statements, DTO objects, and MapStruct interfaces.

Oh, and it actually generates JPA entities from an existing database and gradually update the data model as the database evolves! Yeah.

>> Become a lot more productive with JPA Buddy

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.

2. Maven Dependencies

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


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


3. Understanding Multitenancy in Hibernate

As mentioned in the official Hibernate User Guide, there are three approaches to multitenancy in 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.

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

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

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 provides two implementations of this interface depending on how we define the database connections:

  • 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

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.

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:

public abstract class MultitenancyIntegrationTest {

    private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;

    private SessionFactory sessionFactory;

    public void setup() throws IOException {


        Properties properties = getHibernateProperties();

        sessionFactory = buildSessionFactory(properties);


    protected void initTenant(String tenantId) {

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

class SchemaMultiTenantConnectionProvider
  extends AbstractMultiTenantConnectionProvider {

    private ConnectionProvider connectionProvider;

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

    protected ConnectionProvider getAnyConnectionProvider() {
        return connectionProvider;

    protected ConnectionProvider selectConnectionProvider(
      String tenantIdentifier) {
        return connectionProvider;

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

    private ConnectionProvider initConnectionProvider() throws IOException {
        Properties properties = new Properties();

        DriverManagerConnectionProviderImpl connectionProvider 
          = new DriverManagerConnectionProviderImpl();
        return connectionProvider;

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

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


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:

void whenAddingEntries_thenOnlyAddedToConcreteDatabase() {

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:

class MapMultiTenantConnectionProvider
  extends AbstractMultiTenantConnectionProvider {

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

    public MapMultiTenantConnectionProvider() throws IOException {

    protected ConnectionProvider getAnyConnectionProvider() {
        return connectionProviderMap.values()

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

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

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

hibernate.connection.url=jdbc:h2:mem:<Tenant Identifier>;DB_CLOSE_DELAY=-1

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


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.

Persistence bottom

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

Persistence footer banner
Comments are closed on this article!