Search code examples
javahibernatespring-bootspring-data-jpamulti-tenant

How do you use a fixed database in a multi-tenant (database-per-tenant) aware Spring Boot application


I do have a multi-tenant-aware Spring Boot application (see https://medium.com/swlh/multi-tenancy-implementation-using-spring-boot-hibernate-6a8e3ecb251a) with a bunch of jpa entities that do exist per database. I do have one entity table Tenant though, that is supposed to exist in the default database only and store information about the various tenants (e.g. database name). How do i fix the database for the entity class in a tenant-per-database setup?

In a tenant-per-schema you could conveniently use the @Table annotation for that like follows for example:

@Entity
@Table(name="tenant", schema = "public")
public class Tenant {
...

Does there exist a similar approach for per-database setups?


Solution

  • You'll need to setup multiple datasources, then connect dedicated entity manager to each datasource, then attach JPA repositories for each dedicated entity manager.

    Here is a good sample:

    https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7