How to Implement Multi Tenancy With Hibernate and Spring
Implement multi tenancy with Hibernate: compare discriminator, schema and database per tenant, resolve the tenant per request and avoid cross tenant leaks.

A multi-tenant application serves several customers from one deployment, and the hardest bug it can have is showing one customer another customer's data. Hibernate has first-class support for three isolation models. The choice between them is made once, early, and is expensive to reverse, so this guide spends its first half on choosing and its second half on building the cheapest model correctly. Examples use Hibernate 7 and Spring Boot 4.
Pick the model before writing code
| Model | Isolation | Running cost | Migrations |
|---|---|---|---|
| Discriminator column | Logical, enforced by queries | Lowest | One run |
| Schema per tenant | Strong, enforced by the database | Medium | One run per schema |
| Database per tenant | Strongest, separate resources | Highest | One run per database |
Hundreds or thousands of small tenants with similar data volumes suit a discriminator column. Thirty large tenants with contractual isolation, different backup schedules or their own data residency suit separate schemas or databases. The number that matters is migrations: with schema per tenant, every deployment runs your Flyway scripts once per schema, and a thousand tenants make a ten-second migration into a three-hour release. Count tenants at the size you expect in two years, not today.
Isolation can also be pushed into the database, which protects against application bugs. PostgreSQL row-level security makes the discriminator model much safer, and it is covered in PostgreSQL row level security.
Discriminator with @TenantId
Hibernate 6 and 7 support the discriminator model with one annotation.
@Entity
public class Invoice {
@Id @GeneratedValue
private Long id;
@TenantId
private String tenantId;
private BigDecimal total;
}Hibernate appends tenant_id = ? to every query on the entity, including joins that reach it, and fills the column on insert. The application never sets the field. What it must supply is the current tenant.
@Component
public class TenantResolver implements CurrentTenantIdentifierResolver<String> {
@Override
public String resolveCurrentTenantIdentifier() {
return TenantContext.current().orElse("public");
}
@Override
public boolean validateExistingCurrentSessions() {
return true;
}
}@Bean
HibernatePropertiesCustomizer tenantCustomizer(TenantResolver resolver) {
return props -> props.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, resolver);
}The fallback "public" deserves a decision. Returning a default means a request with no tenant silently reads the shared tenant's rows. Throwing instead turns a missing tenant into a loud failure, which is the safer behaviour for everything except application start-up and migrations. validateExistingCurrentSessions returning true makes Hibernate check that a session opened for one tenant is not reused for another.
Native queries and raw JDBC bypass the filter. A @Query(nativeQuery = true) on an invoice table returns every tenant's rows unless the SQL itself contains tenant_id = :tenant. Review every native query in the project once, and add a test per query.
Schema or database per tenant
For stronger isolation, implement MultiTenantConnectionProvider, which hands Hibernate a connection already pointed at the tenant's schema or database.
@Override
public Connection getConnection(String tenantId) throws SQLException {
Connection connection = dataSource.getConnection();
connection.setSchema(tenantId);
return connection;
}
@Override
public void releaseConnection(String tenantId, Connection connection) throws SQLException {
connection.setSchema("public");
connection.close();
}The release method is the one that causes incidents. Connections come from a pool, so if one is returned to the pool still pointed at tenant 17's schema, the next request on that connection reads tenant 17's data without any error. Always reset the schema on release. Database per tenant usually needs one pool per tenant or a routing data source, and pool sizing across many tenants needs thought; the arithmetic is in HikariCP sizing.
Resolve the tenant once, at the edge
A servlet filter reads the tenant, stores it for the request and clears it afterwards.
try {
TenantContext.set(tenantFrom(request));
chain.doFilter(request, response);
} finally {
TenantContext.clear();
}Take the tenant from something the user cannot edit: a claim in the verified token, or a subdomain checked against the user's memberships. A ?tenant= query parameter that the code trusts lets any user read any other tenant by changing a number. The finally block matters as much, because a thread-local left set leaks into the next request served by that thread. With virtual threads, a ScopedValue binds the tenant to the call instead of the thread and cannot leak.
Caches, jobs and events
The database filter cannot protect a cache. A Caffeine or Redis cache keyed by invoice id returns tenant A's invoice to tenant B if ids collide or if the key ignores the tenant. Put the tenant in every cache key. The same applies to background jobs: a scheduled task has no request, so it must iterate tenants explicitly and set the context for each, and an event handler must receive the tenant in the event payload.
Onboarding a tenant
In the discriminator model, a new tenant is a row in a tenant table and nothing else, which is why it scales to thousands. In the schema model it is a provisioning job: create the schema, run the migrations against it, seed reference data and only then mark the tenant active. Run that job idempotently, because it will fail halfway at some point and need a retry. Keep the list of schemas in a catalogue table rather than discovering them from information_schema, so a half-created schema is never served to a user. Offboarding is the mirror image and deserves the same care: export, retention period, then deletion, with the deletion logged.
Flyway can migrate many schemas from one startup hook by iterating the catalogue. Run it before the application starts accepting traffic, and fail the start if any tenant fails to migrate, so a half-migrated fleet never serves requests.
Test for leaks, not for features
The test that matters creates data for tenant A, switches the context to tenant B and asserts that nothing is visible through every repository method and every native query. Add one test that calls a service with no tenant set and expects an exception. Run the leak tests in CI on every build, because the next developer who adds a native query will not remember this guide.
Migrating an existing single-tenant database
Adding a tenant column to tables that already hold data needs a plan. Add the column as nullable, backfill every row with the id of the first tenant, add the index with the tenant first, then set the column to not null and add it to unique constraints. Existing unique keys become unique per tenant, so a customer number that was unique globally now needs the tenant in the key. Rehearse the migration on a copy, and time it, since the backfill can lock large tables.
Where this guide stops
An internal tool for one customer is not multi-tenant, and adding the machinery costs more than it protects. When tenants need different feature sets or different schemas, the discriminator model strains and a schema-per-tenant design with a shared catalogue is the better fit. Boundaries between modules are discussed in layered versus hexagonal. References: the Hibernate multitenancy chapter and the TenantId Javadoc.


