4
votes

I'm planning to work on a multi-tenancy application and for now I'm just looking at different implementations on the web to understand the requirements needed to implement such task. Hibernate + Spring boot are the technologies I'm planning to use.

From my readings, all the different tutorials are using the same approach which is to declare the data sources in a config file so that session factories are launched with the boot of the application, but I really want to have a higher level of the app, where I can add tenants dynamically and input their data sources informations. This way the application can get the information of the new tenant without the need to touch the config files and re-boot the app.

I thought about having a separate database where I can store my tenants data source credentials or something like that. Can you give me another approach to solve this requirement or a link to an existing implementation that I can refer to.

Thanks

4

4 Answers

2
votes

I got similar requirements in the past.

I implemented DataSource proxy class. The class has tenant resolver and a map of simple DataSources. All the places where we need a DataSource use the proxy.

On any method call e.g. getConnection() it resolves tenant, check whether the map contains already created DataSource (if not a new DataSource is created for the tenant and stored in the DB). Then the same method of real DataSource from the map is invoked.

Tenant resolver is ThreadLocal based where tenant value is stored in a filter (got tenant from request header) and used in the DataSource proxy.

1
votes

What you need to do is using dynamic datasource routing of Spring Framweork via AbstractRoutingDataSource. This answer explains all for you.

1
votes

In my question.I implements MultiTenantConnectionProvider and CurrentTenantIdentifierResolver.And use DataSourceLookup to choose datasource by tenant.This links is helpful to me.

1
votes

Here is a full working example of a database-per-tenant multitenat app I built using Spring Boot 2, Spring JPA (Hibernate), Spring Security 5 running on MySQL.

I have explained how it all works and have shared the entire code too.

Take a look here.