Skip to main content
PreparationZone Logo
PrepZone

JPA Multitenancy

Schema-per-tenant vs discriminator column strategies in Spring Data JPA.

Pass checkpoint below

Why this matters

  • SaaS BookStore scenarios require tenant isolation in every query.
  • Wrong tenant routing is a severity-1 data leak.
  • Hibernate multitenancy hooks tie to security context from JWT or subdomain.

Tenant isolation

L1 · Fresher

SaaS BookStore may serve many bookshops — each tenant's data must not leak across queries.

Discriminator column

L2 · Intermediate

Add tenant_id to rows and filter every query — simplest model, shared schema.

Schema per tenant

L3 · Advanced

Separate schemas increase isolation but complicate migrations and connection routing.

Hibernate multitenancy

L4 · Expert

CurrentTenantIdentifierResolver and MultiTenantConnectionProvider wire tenant context from JWT or subdomain.

Transaction proxy
BEGIN transaction
bookService.placeOrder()Your code
COMMIT or ROLLBACK
Spring wraps your service in a proxy that opens/commits/rolls back the transaction around your method.

Hook

BookStore SaaS hosts many retailers on one deployment. Each tenant’s books must stay isolated in PostgreSQL without copying the entire schema per customer. JPA multitenancy maps tenant identity to the correct data scope.

Discriminator column (shared schema)

Add tenant_id to every row and filter queries:

Java
// learn:fragment
@Entity
@FilterDef(name = "tenantFilter", parameters = @ParamDef(name = "tenantId", type = String.class))
@Filter(name = "tenantFilter", condition = "tenant_id = :tenantId")
public class Book {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "tenant_id", nullable = false)
  private String tenantId;
}

Enable the filter in a @Service method after resolving tenant from JWT or X-Tenant-Id.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • Schema-per-tenant
  • Hibernate 6 resolver
  • BookStore in action
  • Runnable BookStore lab
  • Failure modes in production
  • Connection pool sizing

Test yourself

Answer these before moving on — recall is what makes it stick.