Shared-schema multi-tenancy in Spring Boot + Hibernate: the reference code we actually run
Multi-tenancy is one of those architectural decisions that looks deceptively simple until you start implementing it.
You add a tenant_id column, make sure queries are scoped to the current tenant, and assume you're done.
But what happens when a request has no tenant context? What happens when Spring Security hasn't populated the authentication context yet? What about native queries, background jobs, or writes that attempt to associate an entity with another tenant?
We ran into these questions while building our SaaS application, PresenceWave.
Rather than publish another theoretical explanation of multi-tenancy, I wanted to document the implementation we actually use: shared-schema, discriminator-based multi-tenancy with Spring Boot and Hibernate 6.
We've also extracted the relevant implementation into an open-source repository. It contains the tenant resolution filter, Hibernate integration, write-time validation, database schema and integration tests.
This isn't a library you can add to your build.gradle. It's reference code extracted from our production application, intended to be read alongside this article.
We've deliberately kept some of the rough edges and limitations in the implementation. They're often the most useful part of an engineering discussion.
Three kinds of requests
Before getting into the architecture, it helps to understand the different kinds of requests a multi-tenant application needs to handle.
There are three distinct scenarios:
- No tenant yet. Login, magic-link validation, health checks and other requests that happen before authentication. There's no tenant to scope the request to.
- A tenant from an authenticated session. A logged-in user working within their own tenant. This is the primary use case covered by our reference implementation.
- A tenant resolved from the request, without authentication. For example, a visitor accessing a customer's public blog, links page or embedded widget through that customer's custom domain.
Our TenantResolutionFilter handles the first two scenarios.
The third is also part of our production application, and probably accounts for the largest volume of requests. However, that uses host-based tenant resolution, which is product-specific and outside the scope of this repository.
It's also a somewhat different problem. Public pages are supposed to expose certain information across an anonymous request. The interesting security question there is ensuring that anonymous writes, such as form submissions, are still associated with the correct tenant.
That's worth a separate discussion.
The isolation model, and why we picked it
There are three common ways to isolate tenants in a relational database.
| Model | Isolation | Operational cost |
|---|---|---|
| Database per tenant | Strongest | A connection pool and migration run per tenant. Cost grows with tenant count. |
| Schema per tenant | Strong | Requires a custom MultiTenantConnectionProvider and migrations per schema. |
| Shared schema + discriminator column | Enforced in the ORM | One schema, one migration path. Cheap to add tenants, but isolation depends on queries going through Hibernate. |
We use the third approach.
Hibernate 6 supports discriminator-based multi-tenancy natively. We configure:
hibernate.multiTenancy=DISCRIMINATOR-
@TenantIdon the discriminator column. - A
CurrentTenantIdentifierResolverimplementation.
Hibernate then automatically appends a tenant predicate to queries against tenant-scoped entities and populates the discriminator column on inserts.
We don't need to add WHERE tenant_id = ? to every repository method or pass tenant identifiers through every service call.
The ORM handles that for us.
The honest trade-off is that the isolation guarantee depends on every relevant code path going through Hibernate.
The implementation and test suite are designed to make that boundary explicit.
Architecture
The complete request lifecycle looks like this:
[INSERT ARCHITECTURE DIAGRAM FROM ORIGINAL ARTICLE HERE]
Four components do most of the work:
-
TenantResolutionFilterruns once per request, after Spring Security, and determines whether the request has a tenant. -
TenantContextHolderstores that decision using a pair ofThreadLocalvariables. -
CurrentTenantIdentifierResolverImplconnects Hibernate to the tenant context. -
TenantAwareAspectaddresses a gap that Hibernate's read-side filtering doesn't cover: writes.
Let's look at each component.
Resolving the tenant: a filter that runs after security, on purpose
The tenant resolution filter needs to know who is making the request.
For authenticated requests, it reads the authentication information from Spring Security's SecurityContextHolder and looks up the user's tenant membership.
A simplified version of the implementation:
// web/TenantResolutionFilter.java (trimmed) private void resolveTenant(String path) { if (!path.startsWith(TENANT_SCOPED_PATH_PREFIX)) { // Not a tenant-scoped endpoint: public request, // Hibernate runs in root mode. TenantContextHolder.setPublicRequest(true); return; } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof UserDetails userDetails) { TenantUser membership = tenantUserRepository .findByUserEmail(userDetails.getUsername()) .orElseThrow(() -> new IllegalStateException( "Authenticated user has no tenant membership" ) ); TenantContextHolder.setTenant(membership.getTenant()); } else { TenantContextHolder.setTenant(null); TenantContextHolder.setPublicRequest(true); } } Three outcomes come out of this method:
- A non-tenant-scoped path.
- An unauthenticated API request.
- An authenticated API request.
Only the last one gets an actual tenant assigned.
There are two details here that are easy to get wrong.
1. Filter ordering is important.
Spring Boot registers its security filter chain at order -100.
We register our tenant resolution filter at order 1, after security, because it reads Authentication from SecurityContextHolder.
That authentication context doesn't exist until the security filter chain has run.
Interestingly, our production code used to have a comment saying the opposite: "keep before security".
It was wrong, and we corrected it while extracting the repository.
A stale comment pointing in the wrong direction on something this important is exactly the kind of thing worth checking in your own codebase.
2. The initial tenant lookup cannot itself be tenant-filtered.
When findByUserEmail runs, we don't know the tenant yet. That's precisely why we're running the query.
If it were a normal derived query against an entity annotated with @TenantId, Hibernate would append the tenant discriminator predicate using our fail-closed default tenant ID.
It would find nothing.
So we deliberately use a native query:
// tenant/TenantUserRepository.java (trimmed) @Query( value = """ SELECT tu.* FROM tenant_users tu JOIN users u ON tu.user_id = u.id WHERE u.email = :email """, nativeQuery = true ) Optional<TenantUser> findByUserEmail( @Param("email") String email ); Native queries bypass @TenantId entirely.
That's exactly what we need for this bootstrap lookup, but it's also why every other native query in a tenant-aware codebase needs to be reviewed carefully.
Hibernate's safety net only covers JPQL and derived queries.
Teaching Hibernate who's asking
The next component is CurrentTenantIdentifierResolverImpl.
Hibernate calls this resolver to determine the tenant identifier to use for the current operation.
Here's the relevant implementation:
// tenant/CurrentTenantIdentifierResolverImpl.java public static final Long DEFAULT_TENANT_ID = -1L; // Can never match a real row. Real IDs start at 1. @Override public String resolveCurrentTenantIdentifier() { try { if (TenantContextHolder.getCurrentTenantId() != null) { return TenantContextHolder.getCurrentTenantId(); } } catch (Exception e) { return "" + DEFAULT_TENANT_ID; } return "" + DEFAULT_TENANT_ID; } @Override public boolean isRoot(Object tenantId) { Boolean publicRequest = TenantContextHolder.getPublicRequest(); return publicRequest != null && publicRequest; } Two decisions carry most of the design.
Fail closed, not fail open.
If a request forgets to set a tenant, it doesn't get access to all tenants' data.
It gets no data because -1 cannot match a real tenant ID.
The failure mode of a bug here is an empty result, not an accidental data leak.
isRoot() is the escape hatch.
When isRoot() returns true, Hibernate stops appending the tenant discriminator predicate.
We use this for public requests and background jobs that legitimately need to access data across tenants.
But we're not going to pretend this is a harmless switch.
It is the single riskiest part of this design because the ORM no longer provides automatic tenant isolation for those operations.
We register the resolver explicitly on the EntityManagerFactory, because we build it manually rather than relying entirely on Spring Boot autoconfiguration.
// config/PrimaryDataSourceConfig.java return builder .dataSource(dataSource) .packages("com.example.multitenant") .persistenceUnit("primaryPU") .properties(Map.of( "hibernate.tenant_identifier_resolver", tenantIdentifierResolver )) .build(); Opting an entity in: one extends, two columns
We use a mapped superclass to make entities tenant-aware.
// tenant/TenantAwareEntity.java (trimmed) @MappedSuperclass public abstract class TenantAwareEntity { @Id @Tsid protected Long id; @ManyToOne @JoinColumn(name = "tenant_id") protected Tenant tenant; @TenantId protected String tenantIdFilter; @CreationTimestamp protected LocalDateTime createdAt; @UpdateTimestamp protected LocalDateTime updatedAt; } Notice that we have two tenant-related fields.
They serve different purposes.
-
tenantis a regular foreign-key relationship. It maintains relational integrity and can be used for joins. -
tenantIdFilteris the discriminator column Hibernate uses for automatic tenant filtering.
The discriminator field is a String because that's what our resolver returns.
An entity opts into tenancy simply by extending this superclass.
For example:
// example/Project.java @Entity public class Project extends TenantAwareEntity { @Column(nullable = false) private String name; } The repository doesn't need to know anything about tenants.
// example/ProjectRepository.java public interface ProjectRepository extends JpaRepository<Project, Long> { List<Project> findByName(String name); } There is no tenant parameter in findByName.
Hibernate adds the discriminator predicate automatically.
That's the appeal of this approach: tenant isolation lives in one base class and one resolver, rather than being repeated across every repository method.
The gap Hibernate doesn't close: writes
@TenantId takes care of populating the discriminator column on inserts.
But it doesn't update or validate the tenant relationship.
Nothing inherently prevents application code from constructing an entity that points to another tenant, perhaps using an ID supplied by a client.
We address this with TenantAwareAspect.
The aspect intercepts save() and saveAll() calls across Spring Data repositories.
Here's the relevant code:
// tenant/TenantAwareAspect.java (trimmed) @Before( "execution(* org.springframework.data.repository.CrudRepository+.save(..)) || " + "execution(* org.springframework.data.repository.CrudRepository+.saveAll(..))" ) public void beforeSave(JoinPoint joinPoint) { if (!tenantAwareUtil.hasTenantContext()) { return; } Object entity = joinPoint.getArgs()[0]; if (entity instanceof TenantAwareEntity tenantAwareEntity) { Tenant currentTenant = tenantAwareUtil.getCurrentTenant(); if (tenantAwareEntity.getTenant() == null) { // New entity: stamp it from the current context. tenantAwareEntity.setTenant(currentTenant); tenantAwareEntity.setTenantIdFilter( "" + currentTenant.getId() ); } else if ( !tenantAwareEntity.belongsToTenant(currentTenant.getId()) ) { // Entity points to a different tenant. throw new SecurityException( "Attempt to save entity with mismatched tenant" ); } } } The intended behaviour is straightforward:
- New entity without a tenant: assign the current tenant.
- Existing entity belonging to another tenant: reject the operation.
We throw an exception rather than silently correcting the tenant relationship.
There is, however, a known limitation in this implementation.
The aspect only inspects joinPoint.getArgs()[0].
For save(entity), that argument is the entity itself.
For saveAll(collection), the first argument is a collection. The instanceof TenantAwareEntity check fails, and the call passes through without validation.
So saveAll() currently bypasses this aspect entirely.
We have deliberately left this limitation documented rather than quietly presenting the implementation as complete.
If your codebase relies on saveAll(), this needs to be fixed before adopting the pattern.
It's also a useful reminder that intercepting a repository method doesn't automatically mean you've handled every shape of its arguments.
Proving it, against a real database
Mocking the repository wouldn't prove much here.
The actual guarantee we're interested in is the SQL Hibernate generates and whether the database results respect tenant boundaries.
Our integration tests use Testcontainers to spin up a real PostgreSQL instance.
A simplified version of the tests:
// TenantIsolationIntegrationTest.java (trimmed) @Test void queries_AsAnotherTenant_DoNotSeeTheRows() { TenantContextHolder.setTenant(tenantA); Project alpha = projectRepository.save( Project.builder() .name("alpha") .build() ); TenantContextHolder.setTenant(tenantB); assertThat(projectRepository.findAll()).isEmpty(); assertThat( projectRepository.findById(alpha.getId()) ).isEmpty(); assertThat( projectRepository.findByName("alpha") ).isEmpty(); } @Test void queries_WithoutTenantContext_SeeNothing() { TenantContextHolder.setTenant(tenantA); projectRepository.save( Project.builder() .name("alpha") .build() ); TenantContextHolder.clear(); assertThat(projectRepository.findAll()).isEmpty(); } @Test void save_WithEntityOfAnotherTenant_IsRejected() { TenantContextHolder.setTenant(tenantA); Project foreign = Project.builder() .name("gamma") .tenant(tenantB) .build(); assertThatThrownBy( () -> projectRepository.save(foreign) ) .isInstanceOf(SecurityException.class) .hasMessageContaining("mismatched tenant"); } These tests verify three different behaviours:
- Cross-tenant reads return no results, even when querying by an exact entity ID.
- A missing tenant context results in no data being returned.
- A write attempting to associate an entity with another tenant is rejected.
There's also a fourth test that deliberately sets publicRequest = true and verifies that it can see all tenants' rows.
That's an important test because root mode is a documented trade-off in this architecture.
A test suite that doesn't verify this behaviour would be hiding one of the most important parts of the design.
What we didn't smooth over
We left the limitations in the README rather than fixing everything before publishing.
These are useful considerations for anyone implementing this architecture.
1. Context doesn't automatically follow work onto other threads.
TenantContextHolder uses TransmittableThreadLocal.
However, that doesn't mean context propagation is automatically configured.
It requires TTL-aware executors or the TTL Java agent, neither of which is wired up in this reference repository.
A plain @Async method or @Scheduled job needs to set the tenant explicitly and clear it in a finally block.
Otherwise, it runs without a tenant context.
2. saveAll() bypasses the aspect.
As explained earlier, our aspect only inspects the first method argument as an entity.
A collection passed to saveAll() isn't inspected.
This needs to be addressed before relying on the aspect for collection writes.
3. Public requests are unfiltered.
When isRoot() returns true, Hibernate doesn't append the discriminator predicate.
There is no softer version of this behaviour.
Isolation for those requests depends on the application handler, not Hibernate.
4. Native queries are outside the safety net.
The initial tenant membership lookup deliberately uses a native query.
That's necessary because we don't know the tenant when performing the lookup.
But every other native query against tenant-scoped data needs to implement its own tenant restrictions.
5. The discriminator column needs an index.
The tenant discriminator should lead its own index.
Otherwise, tenant-scoped queries can end up scanning the table.
Our reference migration, V1__tenancy_core.sql, adds these indexes.
It's easy to overlook this when adding new tenant-aware tables later.
What's not here
This repository is intentionally scoped to the tenancy plumbing.
It doesn't include:
- Resolving tenants from custom domains.
- API-token authentication.
- Tenant invitations and membership management.
- Product-specific authorization rules.
- Public visitor handling and anonymous form submissions.
Those are separate concerns from the narrower question of how Hibernate knows which tenant's rows it should return.
Try it, read it, take it apart
We've published the implementation as an open-source reference repository:
GitHub: https://github.com/JulioLabs/spring-boot-multitenant-starter
The README includes a suggested reading order:
TenantContextHolderCurrentTenantIdentifierResolverImplTenantAwareEntity- Configuration
TenantResolutionFilterTenantAwareAspect- The isolation integration test
The docs/architecture.md file goes deeper into the request lifecycle and the implications of public-request handling.
We built this because we needed it for our own SaaS application, PresenceWave.
If you're evaluating shared-schema discriminator-based tenancy against schema-per-tenant or database-per-tenant, hopefully seeing a real implementation — including its limitations — is more useful than another abstract description of the pattern.
I'd particularly welcome feedback from people who have implemented multi-tenancy with Hibernate:
- Have you encountered other edge cases with
@TenantId? - How do you handle tenant context propagation across asynchronous execution?
- How do you enforce tenant consistency on bulk writes?
- Have you found a better way to handle public or root-mode requests?
The intention here is to share something useful with the Java community and learn from people who have tackled the same problems.
