Search code examples
javaspringhibernatemulti-tenant

Change current schema before using spring data Repository - Multi tenancy


I am using a multi tenant spring boot web application which reads some data from a database.

I have built schema per tenant model, implementing MultiTenantConnectionProvider and CurrentTenantIdentifierResolver to set connections based on the tenant. The tenant is resolved using a ThreadLocal variable, set in a Filter (built by extending OncePerRequestFilter).

However, I need to solve for a specific case where I do not get the tenant information at the filter. I can however, get the tenant information later while processing the request in a service, but by this time the entity manager is set (seems to be done by OpenSessionInViewFilter looking at spring sources) to use the default schema and all my queries fail because the default schema do not contain the data I need.

My question is, how do I set the entity manager to point to the tenant specific schema at service level, after the hibernate filter has already set the session? I could do whatever the filter (OpenSessionInViewFilter) is doing, something like the below:

   EntityManager entityManager = entityManagerFactory.createEntityManager();
   TransactionSynchronizationManager.bindResource(entityManager, new EntityManagerHolder(entityManager));
   //unbind once I am done using the repositories

But I was thinking if this is the right way or if there is any other better, easier, documented way.


Solution

  •    EntityManager entityManager = entityManagerFactory.createEntityManager();
       TransactionSynchronizationManager.bindResource(entityManager, new 
       EntityManagerHolder(entityManager));
    

    The above didn't work for me. However, I found a workaround - by running my task in a different thread (I just created a fixed thread pool executor and submitted my tasks) and setting the new tenant in a ThreadLocal object, I was able to achieve what I wanted. With the right CurrentTenantIdentifierResolver and MultiTenantConnectionProvider implementations, a connection to the expected tenant schema got established.