Back to Blog Archive

Multi-Tenancy using JPA, Spring and Hibernate – Part One

Posted on: November 22, 2016
Jose M

Multi-tenancy allows an application to behave as multiple independent applications hosted for different clients (i.e. organisations). This might not sound impressive, however as the number of clients increase it becomes more evident that it is easier and more cost effective to run a single application hosted for all the clients rather than hosting an independent application for each client.

Multi-tenancy has become more popular lately and is very useful for the economy in software companies since it makes your service more affordable using cheaper installations/costs. This is because multi-tenancy can lead your business to a higher level of competitive differentiation.

How does multi-tenancy work?

Multi-tenancy allows a single application instance to be served for multiple tenants on a single hosting server. This is usually performed by either Separating databases, Separating schemas or Sharing schemas.

This architecture therefore allows for a single instance to service different companies.


Multi-tenancy works by using the concept of tenants, each tenant has access only to his corresponding data, even if they are in the same or different database. It means that you can have multiple tenants (usually one per client) who will use your application as if it were a single application. Amazing, isn’t it?

Multi-tenancy implementation – software architecture

Let’s start with the basic, multi-tenancy has 3 different ways to implement:

  • Separate-databases: Each tenant has its own database
  • Separate schemas: Tenants share common database but each tenant has its own set of tables (schema)
  • Shared schema: Tenants share common schema and are distinguished by a tenant discriminator column

No choice is better than another, every choice has different advantages and disadvantages, therefore it all boils down to what you want to compromise:

  • Quantity of tenants
  • Performance
  • Time of development
  • Reliability
  • Disaster recovery
  • And so on…

When you want to achieve a feature, it usually brings down another.

For instance: Separate-database is fully isolated, also it provides backup easily per tenant, however its performance isn’t so good as shared schema when there are a lot of clients.

Multi-tenancy implementation

Hibernate, Spring, JPA

In this section we are going to use the Java specification for accessing POJOs to relational databases, that is the Java Persistent API (JPA).

As discussed earlier in the blog post, there are different approaches to implement Multi Tenancy, in this example we are going to use a separate database per tenant. In order to access the database we are going to use Hibernate which is a JPA Implementation.

We have chosen Hibernate because it is a well known ORM which has provided support for multi-tenancy implementation since version 4.  To use Hibernate with your Java application all you need to do is to implement two interfaces: MultitenantConnectionProvider and CurrentTenantIdentifierResolver.

Your custom implementation of these classes will mainly differ based on your chosen multi-tenancy implementation architecture as described in the previous sections. However, it should be noted that Hibernate does not yet support the shared schema architecture (see HHH-6054).

Hibernate sessions

Through the use of these sessions Hibernate is able to create transactions on entities. A session is opened and closed per transaction, when the session is created the tenantId is specified. Through the use of the tenantId, Hibernate can determine which resources to use, such that a tenant would access its (and only its) database.

In order to be able to create sessions, the SessionFactory class can be used. The SessionFactory needs to be provided with the tenantId so it is able to create a session appropriate to the database/schema that would be used by the tenant of the session being created. Below is an example of how a session is created:

Note: Since we use JPA, we don’t have to use the above code because Hibernate sessions are created automatically by JPA.

Note: Also, don’t confuse Hibernate sessions with Http sessions, one is for database transactions, the other is for a user across more than one page request.

Implementation Details

MultitenantConnectionProvider and CurrentTenantIdentifierResolver

So now that we know how Hibernate works for multi-tenancy, some more questions can arise.

How does Hibernate know what database or schema to choose in multi-tenancy?

This is done through our custom implementation of MultitenantConnectionProvider. Our implementation provides a different connection by tenantId. This connection is then used for the Hibernate session.

How does Hibernate know which tenant to use?

For that we must implement CurrentTenantIdentifierResolver, this class has a method called resolveCurrentTenantIdentifier()  that resolves the issue of which tenantId must be used by hibernate when a session is created.

Let’s implement MultitenantConnectionProvider. We have the interface class MultitenantConnectionProvider which has the next implemented classes by hibernate:

For our purpose, we want to provide connections to different databases through several DataSources. For that we could use a map<TenantId, DataSource>, in this way we’d get the DataSource by the tenantId. Also we could extend DataSourceBasedMultiTenantConnectionProviderImpl but it uses jndi. As we will not use jndi in this post, we implement AbstractMultiTenantConnectionProvider instead:

DataSourceLookup bean has a map with different datasources mapped by his tenant id, we will write a new post about possible ways to implement this class and how we did it. This will answer the question “how does Hibernate/Spring know what tenants exist?

CurrentTenantIdentifierResolver can be implemented in different ways. In our case we decided to take the tenantId from an httpSession attribute. And this is used in throughout Hibernate in this interface.

 How do we integrate Multi-tenancy with JPA?

To integrate with JPA you must set the jpaPropertyMap(Map<String, ?> properties) in LocalContainerEntityManagerFactoryBean like this:

If you are using Spring, this can be set in applicationContext.xml.

In future blog posts we will cover the following topics:

  • DataSourceLookup implementation for multi-tenancy
  • Hibernate schema export in multi-tenancy
  • Different ways to save the tenant id in an http session

Finally, I want to share some useful links with you, they helped me to understand Multi-tenancy in Hibernate and JPA.

Useful links




Jose M

6 Comments for “Multi-Tenancy using JPA, Spring and Hibernate – Part One”

  1. Matt Trousdale says:

    Thanks for the simple to follow example. I am sure this will be easy to seamlessly
    integrate to JPA Data Springboot too!

  2. Mahendher says:

    Thanks for sharing the information , Could you pls share the sample project code to implement the same.

  3. hamza seven says:

    could you share as this proptotype project please !
    Can you tell if there is another strategy to store the tenant_id during runing application rather than httpsession ? tnx

    • Jose M says:

      I don’t have a prototype, I have worked in a private project which I shared part of the code. Yes, you can use another strategy in the CurrentTenantIdentifierResolverImpl.resolveCurrentTenantIdentifier() method where you can take the tenant in the way that you wish 🙂

  4. Sunit Katkar says:

    Your article was helpful to get some points cleared for me.

    I have built a complete database-per-tenant multi-tenant web app just like many SaaS style web apps. Its built using Spring Boot 2, Spring JPA (Hibernate) and the web access is secured using Spring Security 5. Take a look here for the blog post I wrote and the complete code I have shared. Please do give your feedback.


    • Jose M says:

      Hello there! I am glad that my post helped you to understand better some points.

      I read your article and I liked, It has very different technologies and a different way to get the tenant, furthermore people can use your github project as a template :).
      Spring boot is the most used form today in Spring applications so your link will be beneficial for people coming to this post too.


Contact Us

Ricston Ltd.
Triq G.F. Agius De Soldanis,
Birkirkara, BKR 4850,
MT: +356 2133 4457
UK: +44 (0)2071935107

Send our experts a message

Need Help?
Ask our Experts!