Multi Tenant Architecture – 2

As mentioned in the previous post, Multi tenant architecture can be achieved via the following 3 ways:

  • Separate SCHEMA
  • Separate DATABASE
  • DISCRIMINATOR field

Spring Framework in Java does have an easy way to implement Separate Schema, Separate DB & Discriminator based multi tenant architecture.

However, you might have noticed that Multi tenant architecture implementation does not talk about the case – DIFFERENT TABLE PER TENANT

DIFFERENT TABLE PER TENANT

If you need to implement such a case in Java using Spring Framework then Spring does not provide out of the box way to have such kind of an implementation.

Dynamic creation of tables at run time is not possible using Spring JPA. All the entity classes have to be associated with their corresponding tables during boot up. In other words, Spring Data JPA works mostly with static schema.

Thus, dynamic tables creation (in order to obtain a multi tenant architecture) can be achieved by using entity Manager instance and writing native SQL queries  – by creating tables per tenant on the go and doing manual inserts, updates as and when required.

This, by default, when using Spring is done using DAO (Data access object) that provides a common interface to perform database operations with methods like save(), update(), findAll() which behind the scenes are doing native SQL queries.

References:

  1) Multi Tenancy Definition: https://en.wikipedia.org/wiki/Multitenancy

  2) Entity Manager:  https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html