Connecting to tenant databases as per the user login using Hibernate and Spring

652 views Asked by At

I have been reading through multitenancy in hibernate and couple of post from stackoverflow but it seems they are not addressing the requirement that i have, so here it is. I am working on a SAAS based application model where i have one application been served by multiple customers, and for every customer there will be a independent instance of the tenant database(postgresSql). Apart from this i also have a master database that will be used to authenticate the user and to identify which tenant database it belongs, consider this master database will have information like the connection URL to the tenant database.

When the user logs in i will authenticate it with the master database get the tenant database information like connection URL and connect to that database and serve all the users request through that.

Considering the fact that i can define multiple sessionfactories in the hibernate config file, which will make it static during application development, instead i would want to create the sessionfactories dynamically for the respective tenant database for which the user belongs by reading the information of the connection URL from the master database.

Also, there also will be a scenario where in i will have to maintain the sessionfactory of the master database and the tenant database as there will be a requirement where i will have to add users to both master database and tenant database during user creation.

Can any one help be address this requirement?

1

There are 1 answers

0
Pirulino On

I would define two sessionfactory, one for the master db and one for the others dbs starting with fake values. this can help you on how to change the datasource at run time.

Finally threadlocal can help you to store data between calls.

Hope it helps.