Multi-Tenancy support when using Hibernate with Spring

I am trying to add multi-tenancy support in my existing application. I would prefer to use “schema” multi-tenancy. I have read documentation about how hibernate provides support for multi-tenancy. I have read about MultiTenantConnectionProvider and CurrentTenantIdentifierResolver. I see examples about how I can add my tenant identifier when I create the session, such as:

Session session = sessionFactory.withOptions()
.tenantIdentifier( yourTenantIdentifier )

.openSession();

My problem is that i never explicitely create the session. i am using hibernate along with Spring and the transaction in my service layer is creating the hibernate session for me. Is this my problem? Am I going to need to move away from this and manage transactions and the session explicitely in my own code?

In addition, I use DataSources defined in the container I am running in, such as Tomcat. I am using the connection pool it supports. I never create a connection myself in my own code. I am confused how I can use hibernate’s multi-tenancy support using the implementation I have. I could use some direction getting started.

My problem is that i never explicitely create the session. i am using hibernate along with Spring and the transaction in my service layer is creating the hibernate session for me. Is this my problem? Am I going to need to move away from this and manage transactions and the session explicitely in my own code?

You only need to configure the LocalContainerEntityManagerFactoryBean to use multitenancy, as explained in this article.

In addition, I use DataSources defined in the container I am running in, such as Tomcat. I am using the connection pool it supports. I never create a connection myself in my own code. I am confused how I can use hibernate’s multi-tenancy support using the implementation I have. I could use some direction getting started.

You need either DataSource instances especially because connections are pooled. So, you need to configure Tomcat to provide you 2 DataSource(s), one for each schema. Then, the article I provided you already shows you how to select the right DataSource based on the current tenant identifier.

Thanks for the quick reply. So it sounds like I will need a separate datasource for each tenant? There isn’t a way I could share my datasource connection pool across tenants?

You could switch the current schema like this if the DB supports that:

ALTER SESSION SET CURRENT_SCHEMA = <schema name>