Java.Hibernate.Middle.How do you handle multi-tenancy with Hibernate?

Short Answer

Hibernate supports multi-tenancy via its built-in multi-tenancy API, which allows you to isolate data per tenant at the database, schema, or discriminator level by:
✅ Choosing a multi-tenancy strategy (DATABASE, SCHEMA, or DISCRIMINATOR).
✅ Implementing MultiTenantConnectionProvider (provides connections per tenant).
✅ Implementing CurrentTenantIdentifierResolver (determines current tenant ID).

🔎 Main multi-tenancy strategies

Hibernate supports three strategies:
1️⃣ DATABASE → each tenant has a separate database.
2️⃣ SCHEMA → one database, each tenant uses a separate schema.
3️⃣ DISCRIMINATOR → all tenants share the same tables, but a tenant_id column distinguishes them.


🔹 How does it work technically?
✅ You configure Hibernate’s multi-tenancy mode:

hibernate.multiTenancy=SCHEMA

✅ Implement MultiTenantConnectionProvider → returns a DB connection appropriate for the current tenant.

public class SchemaMultiTenantConnectionProvider implements MultiTenantConnectionProvider {
    @Override
    public Connection getConnection(String tenantIdentifier) throws SQLException {
        Connection connection = dataSource.getConnection();
        connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
        return connection;
    }
    // other methods...
}

✅ Implement CurrentTenantIdentifierResolver → returns tenant ID for the current request:

public class HeaderTenantIdentifierResolver implements CurrentTenantIdentifierResolver {
    @Override
    public String resolveCurrentTenantIdentifier() {
        return TenantContext.getCurrentTenant(); // e.g., from a ThreadLocal or request header
    }
    @Override
    public boolean validateExistingCurrentSessions() {
        return true;
    }
}

🔹 How they work together
1️⃣ A request comes in → your code sets the current tenant ID in a TenantContext (ThreadLocal).
2️⃣ Hibernate calls CurrentTenantIdentifierResolver → gets tenant ID.
3️⃣ Hibernate passes the tenant ID to MultiTenantConnectionProvider.
4️⃣ Your provider configures the connection → sets schema or picks DB based on tenant ID.


🔹 Hibernate configuration example

hibernate.multiTenancy=SCHEMA
hibernate.tenant_identifier_resolver=com.myapp.HeaderTenantIdentifierResolver
hibernate.multi_tenant_connection_provider=com.myapp.SchemaMultiTenantConnectionProvider

📊 Comparison of strategies

StrategyIsolationComplexityUse case
DATABASEHighestHighRegulated industries, strict data separation
SCHEMAMedium-highMediumSaaS apps with moderate isolation needs
DISCRIMINATORLowest (soft)LowestMany small tenants, low security demands

📌 Key Takeaways

✅ Hibernate multi-tenancy allows you to reuse a single app for multiple tenants with clear data isolation.
✅ Choose the right strategy: DATABASE for maximum security, SCHEMA for balance, DISCRIMINATOR for simplicity.
✅ Implement MultiTenantConnectionProvider + CurrentTenantIdentifierResolver → core of multi-tenancy.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.