Skip to main content

Hibernate 8 Safe Mode for HQL and Row-Level Security Multi-Tenancy on PostgreSQL (8.0.0.CR2)

Hibernate ORM 8.0.0.CR2 (release candidate) adds hibernate.query.safe_mode_enabled, which rejects HQL calls to unregistered database functions, and generates a PostgreSQL row-level-security policy for @TenantId tables. Both run against a real PostgreSQL 16 with captured output: what each blocks, what a superuser bypasses, how a set_config() call moves the tenant, and the tenant parameter in @SQLUpdate and @SQLDelete.

Multi-tenancy with a shared table means every row carries a tenant_id and every query must filter on it. Forget it once, in one report or one native query, and one customer reads another customer’s data. Hibernate ORM 8 adds two defences against that, and both are new: a safe mode that stops HQL from calling database functions nobody registered, and a generated PostgreSQL row-level-security policy for every @TenantId table. This post turns each one on against a real PostgreSQL 16, prints what actually happened, and shows where each one stops protecting you.
Versions tested (pre-release). Hibernate ORM 8.0.0.CR2, a release candidate whose jar Maven Central dates 24 Nov 2026. It is not a Final release: maven-metadata.xml lists 8.0.0.Alpha1, Beta1–Beta4, CR1 and CR2 as the newest 8.x entries, with 7.4.17.Final as the newest 7.x, and the release page warns 8.0 features may change incompatibly. Both settings in this post are marked @Incubating(since = "8.0") in the CR2 sources. PostgreSQL 16.15, pgjdbc 42.7.15, JDK Temurin 25.0.5.1, JUnit 6.1.3, Maven 3.9.11. Treat every behaviour below as CR2 behaviour. The Inkflow backlog note for this topic said to wait for Hibernate 8 GA; I wrote it against CR2 because both features exist and run, and I say so wherever it matters.

Two holes in “we always filter by tenant”

With @TenantId on an entity, Hibernate adds tenant_id = ? to the HQL it generates. That covers the code path most people write. It does not cover a createNativeQuery, a reporting script, a developer who connects with psql, or HQL that calls a database function you did not expect. Hibernate 8 answers two of those holes with two separate switches, and they sit at different layers.
Where each protection sitsHQL / Criteriayour query text1. safe modeunknown function? stop2. @TenantId filteradds tenant_id = ?3. PostgreSQL RLSpolicy on the tableNative SQLcreateNativeQueryPlain JDBCreports, scripts, a bugno safe-mode checkno Hibernate filterDashed paths skip the first two layers. Only the database policy sees every statement, which is why it is the last line.
Read the diagram left to right for HQL: first the new safe-mode check on the query text, then the tenant filter, then the database. Native SQL and plain JDBC take the dashed path and meet only the last box. The PostgreSQL policy is the only layer that sees every statement, and safe mode is the only layer that looks at what an HQL query is allowed to call. Neither replaces the filter you already have. The companion module is one self-contained Maven module, hibernate8-jpa4-demo / rls-safe-mode. Two small entities carry the whole post, Invoice and Receipt, and five test scenarios write the transcripts quoted below into output/. Each test asserts the same facts, so a figure that stops being true fails the build.

Safe mode: HQL may only call functions someone registered

HQL lets you call any database function by name. If Hibernate does not know the name it passes it through to SQL as written. That is convenient, and it is also how an attacker who controls part of an HQL string can run something like set_config through your connection. Safe mode closes that: the setting is hibernate.query.safe_mode_enabled, default false, and with it on an unknown function raises an exception at parse time. The Javadoc says it covers HQL and Criteria queries. The test class sets it in Lab.java:
var cfg = new HibernatePersistenceConfiguration("lab")
        .managedClasses(Invoice.class, Receipt.class)
        .property("hibernate.connection.provider_class", SqlRecorder.class.getName())
        .property("hibernate.tenant_identifier_resolver", new TenantContext())
        .property("hibernate.query.safe_mode_enabled", Boolean.toString(safeMode))
        .property("hibernate.multi_tenant.rls_enabled", Boolean.toString(rls))
        .property("jakarta.persistence.schema-generation.database.action", "drop-and-create");
The scenario then runs nine calls twice, once with safe mode off and once on. Source: RlsSafeModeTest.java, method safeModeBlocksUnregisteredFunctions. Two of the nine, so you can see the shape:
new Q("set_config()       unregistered", s -> s.createSelectionQuery("select set_config('hibernate.tenant_id', 'tenantB', true)", String.class).getSingleResult()),
new Q("criteria sql()", s -> {
    HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
    var q = cb.createQuery(String.class);
    var root = q.from(Invoice.class);
    q.select(cb.sql("lower(?)", String.class, root.get("customer")));
    return s.createSelectionQuery(q).getResultList();
}),
Real output, safe mode off first and on second (01-safe-mode.txt):
hibernate.query.safe_mode_enabled=false
  upper()            built in        ok: [ALICE, BOB]
  initcap()          contributed     ok: [Alice, Bob]
  quote_ident()      unregistered    ok: [alice, bob]
  current_setting()  unregistered    ok: tenantA
  set_config()       unregistered    ok: tenantB
  sql('...')         raw SQL         ok: [alice, bob]
  criteria function()                ok: tenantA
  criteria sql()                     ok: [alice, bob]
  translate()        built in on PostgreSQL ok: [xlice, bob]

hibernate.query.safe_mode_enabled=true
  upper()            built in        ok: [ALICE, BOB]
  initcap()          contributed     ok: [Alice, Bob]
  quote_ident()      unregistered    rejected: SemanticException: Function [quote_ident] is not allowed in safe mode [select quote_ident(i.customer) from Invoice i order by i.id]
  current_setting()  unregistered    rejected: SemanticException: Function [current_setting] is not allowed in safe mode [select current_setting('hibernate.tenant_id')]
  set_config()       unregistered    rejected: SemanticException: Function [set_config] is not allowed in safe mode [select set_config('hibernate.tenant_id', 'tenantB', true)]
  sql('...')         raw SQL         rejected: SemanticException: Function  is not allowed in safe mode [select sql('lower(?)', i.customer) from Invoice i order by i.id]
  criteria function()                rejected: SemanticException: Function [current_setting] is not allowed in safe mode
  criteria sql()                     rejected: SemanticException: Function  is not allowed in safe mode
  translate()        built in on PostgreSQL ok: [xlice, bob]
Off: everything runs, including set_config(), which returned tenantB to a session logged in as tenantA. On: current_setting, set_config, quote_ident, sql() and both Criteria equivalents are rejected with SemanticException, and the message names the function. upper still works because Hibernate registers it. translate also still works, and that is worth noticing: the allow-list is not “portable HQL functions”, it is every function the PostgreSQL dialect registers, which is a long list. Safe mode keeps out the names nobody registered; it does not shrink the registered ones. To allow one more function, register it. Hibernate calls every FunctionContributor it finds through ServiceLoader. This one is AppFunctions.java:
@Override
public void contributeFunctions(FunctionContributions contributions) {
    var string = contributions.getTypeConfiguration().getBasicTypeRegistry().resolve(StandardBasicTypes.STRING);
    contributions.getFunctionRegistry()
            .namedDescriptorBuilder("initcap")
            .setExactArgumentCount(1)
            .setInvariantType(string)
            .register();
}
and it is listed in META-INF/services/org.hibernate.boot.model.FunctionContributor:
com.ankurm.tenant.AppFunctions
The initcap() row above ran under safe mode because of this class and nothing else. Contributors with an ordinal of 1000 or higher are reserved for application code by the SPI Javadoc, and the default is 1000.
Reference: where the check lives in the CR2 sources I read these from the CR2 -sources.jar, not from the docs. The message text and the guarded call sites come from SemanticQueryBuilder and SqmUtil.failIfSafeModeEnabled:
  • An unregistered function name in HQL calls failIfSafeModeEnabled, which throws SemanticException("Function [name] is not allowed in safe mode", query), with the name lower-cased. output/01-safe-mode.txt shows that text for real.
  • The registered function sql is rejected by name too, in both HQL (sql('lower(?)', i.customer)) and Criteria (cb.sql(...)). Both are in the transcript.
  • The HQL column(...) function is guarded the same way in the source. I did not run it, so that one is read, not verified.
  • Criteria goes through SqmCriteriaNodeBuilder, which reads the same option, and the transcript shows cb.function(...) and cb.sql(...) rejected.
  • Native queries are not parsed by the HQL parser, so the setting does not touch them. The Javadoc scopes it to HQL and Criteria and I did not test native SQL against it.
Safe mode is not SQL-injection protection. It rejects unknown function names. It does not stop a concatenated where clause from changing which rows match, because or 1=1 calls no function. Keep binding parameters. Treat safe mode as a second fence that limits what a successful injection could call.
Going deeper

Row-level security: Hibernate writes the policy for you

Row-level security (RLS) moves the tenant rule from application code into the table. PostgreSQL attaches a policy to a table, and every statement against it, from anyone, only sees or writes rows the policy allows. The policy needs to know the current tenant, so the application tells the database at the start of each transaction. Hibernate 8 does both halves: it creates the policy when it generates the schema, and it sends the tenant at transaction start. The entity is Invoice.java. Nothing in it mentions RLS; @TenantId is enough:
@Entity
@Table(name = "invoice")
public class Invoice {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;

    @TenantId
    @Column(name = "tenant_id", nullable = false)
    public String tenant;

    public String customer;

    public int cents;
The setting is hibernate.multi_tenant.rls_enabled. Per its Javadoc it defaults to true and applies when the database supports it, so here it is only ever turned off. After the schema was created, a superuser connection read the catalog (02-generated-rls-policy.txt, trimmed to the invoice table):
select relname, relrowsecurity, relforcerowsecurity from pg_class (invoice, receipt)
  invoice  rowsecurity=true  force=true
  receipt  rowsecurity=true  force=true

select tablename, policyname, cmd, qual, with_check from pg_policies
  table=invoice policy=hibernate_tenant_isolation cmd=ALL
    using      (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
    with check (((tenant_id)::text = ((NULLIF(current_setting('hibernate.tenant_id'::text, true), ''::text))::character varying(255))::text) OR COALESCE((NULLIF(current_setting('hibernate.tenant_id_root'::text, true), ''::text))::boolean, false))
Two things matter. rowsecurity=true turns RLS on, and force=true makes the policy apply even to the role that owns the table, which is the role Hibernate connects as here; I did not test what happens without FORCE. And the policy compares tenant_id with a session setting called hibernate.tenant_id, or lets the row through when hibernate.tenant_id_root is true. A second run with the setting off (02b-rls-disabled.txt) shows the switch really creates nothing:
hibernate.multi_tenant.rls_enabled=false
  policies=0  tables with row security=0
How does the setting get there? In the CR2 sources, PostgreSQLRowLevelSecurity runs select set_config('hibernate.tenant_id', ?, true), set_config('hibernate.tenant_id_root', ?, true) when a transaction begins, and AbstractSharedSessionContract throws if RLS is on and no tenant is set.
One transaction, one tenant1. begin2. set_config(‘hibernate.tenant_id’, ?, true)3. your queries4. commitThe third argument, true, makes the setting local to the transaction. Commit or rollback erases it, so the nexttransaction on the same pooled connection starts with no tenant at all, and the policy then matches no rows.Step 2 is what the table policy reads. Whoever can run step 2 with another value chooses the tenant.
The timeline shows why the true argument matters. PostgreSQL defines it as “local to the current transaction”, so commit erases the value and a pooled connection cannot carry tenantA into the next request. The demo does not use a pool, so that part is the PostgreSQL contract, not something I measured.
Reference: the policy-generation pieces in the jar
  • org.hibernate.binder.internal.TenantIdBinder adds the tenant_id = :tenantId filter and, when RLS is enabled, asks the dialect for DDL. The policy is named hibernate_tenant_isolation in PostgreSQLRowLevelSecurity, and the transcript shows that name.
  • The DDL runs in the AFTER_TABLES phase: enable row level security, force row level security, then create policy.
  • The jar also contains a DB2RowLevelSecurity class and a TenantIdentifierSource enum with SESSION and DATABASE_USER. The second is picked when a tenant credentials mapper is configured, and then the policy compares the column with current_user instead of a session variable. I did not run either; I saw them in the sources.
Going deeper

What RLS catches that the Hibernate filter cannot

Two tenants, three rows: tenantA owns two invoices, tenantB owns one. The test (method rlsProtectsWhatTheHibernateFilterCannot in RlsSafeModeTest.java) asks the same question four ways. Output (03-isolation.txt):
rls_enabled=true. Rows: tenantA=2, tenantB=1
  tenantA  HQL  select count(i) from Invoice i             -> 2
  tenantA  native  select count(*) from invoice            -> 2
  SQL that reached PostgreSQL for the native query:
    select set_config('hibernate.tenant_id', ?, true), set_config('hibernate.tenant_id_root', ?, true)  [tenantA, false]
    select set_config('hibernate.tenant_id', ?, true), set_config('hibernate.tenant_id_root', ?, true)  [tenantA, false]
    select count(*) from invoice  []
  tenantA  native insert for tenantB                       -> rejected: PSQLException: ERROR: new row violates row-level security policy for table "invoice"
  admin (root)  HQL count -> 3   native count -> 3
  no tenant set                                            -> rejected: HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified

Outside Hibernate, on plain JDBC connections:
  role app, no tenant variable set        select count(*) -> 0
  role app, after set_config('...','tenantB') select count(*) -> 1
  role postgres (superuser)               select count(*) -> 3
  role app      superuser=false bypassrls=false
  role postgres superuser=true bypassrls=true

rls_enabled=false. Same data.
  tenantA  HQL count -> 2   native count -> 3
Read it top to bottom.
  • HQL and native both return 2 for tenantA. The HQL count is filtered by Hibernate (tenant_id = ?). The native select count(*) from invoice has no filter at all, yet it also returns 2, because PostgreSQL applied the policy.
  • The tenant is set twice per transaction. The recorded SQL shows the same set_config statement twice before the query. I observed it and did not investigate why.
  • A forged insert is refused. tenantA tried to insert a row for tenantB and PostgreSQL answered new row violates row-level security policy. The policy’s with check half is what does that.
  • The root tenant sees everything. admin (marked root in TenantContext.java) gets 3 from both queries, so for a root tenant Hibernate also stopped filtering HQL.
  • No tenant, no query. Hibernate throws HibernateException instead of running the query.
  • The last block is the one to remember. On a plain JDBC connection with no tenant set, the app role sees 0 rows. After set_config('hibernate.tenant_id', 'tenantB', false) the same connection sees tenantB’s row. The superuser sees all 3.
The final two lines of the transcript explain the superuser result: postgres has superuser=true bypassrls=true, app has neither. PostgreSQL skips RLS entirely for those. If your application connects as a superuser, or as a role with BYPASSRLS, you have the policy on paper and nothing at runtime. The module’s setup-postgres.sh creates the role with nosuperuser nobypassrls for that reason. And the closing block shows what you get with rls_enabled=false: HQL returns 2 and the native count returns 3.
The session variable is not a secret. Anything that can run SQL as the application role can set hibernate.tenant_id to another value, as the transcript shows on a plain connection. RLS here protects you from your own mistakes: a forgotten filter, a native query, a script. It does not protect you from hostile code that already holds the application’s database credentials. The sources show a credentials-mapper route where each tenant connects as its own database user; I read that, I did not run it.
Going deeper

Why you want both: a function call that moves the tenant

Here is the point where the two features meet. The RLS policy trusts the session variable. A function call from HQL can change the session variable. The scenario in RlsSafeModeTest.java (method aFunctionCallCanMoveTheTenant) models a hostile HQL fragment that runs select set_config('hibernate.tenant_id', 'tenantB', true), followed by the application’s own native count in the same transaction. Output (04-function-moves-tenant.txt):
safe_mode_enabled=false. tenantA runs a hostile HQL fragment, then the app counts rows natively in the same transaction.
  hostile set_config(): ran
  native count afterwards -> ok: 1

safe_mode_enabled=true. tenantA runs a hostile HQL fragment, then the app counts rows natively in the same transaction.
  hostile set_config(): blocked (SemanticException)
  native count afterwards -> ok: 2
Without safe mode the call runs, and the native count that follows returns 1: tenantB’s row, because the policy now believes the session belongs to tenantB. With safe mode the call is rejected before it reaches the database and the count stays at 2. This is a contrived two-step to show the mechanism, not an exploit recipe. Hibernate’s own tenant_id = ? filter still protects the HQL that follows. What the transcript proves is narrower and still useful: an unregistered function in HQL can rewrite the state RLS depends on, and safe mode refuses it. Going deeper

Custom SQL: Hibernate 8 binds the tenant for you

@SQLUpdate and @SQLDelete replace the SQL Hibernate would generate. Hibernate then runs your text as written and adds no tenant predicate, so the predicate has to be yours. CR2 lets the statement declare one extra trailing ? for the session tenant; it is bound to null for a root tenant, which is why the Javadoc example ends with coalesce(?,tenant_id). The entity is Receipt.java:
@Entity
@Table(name = "receipt")
@SQLUpdate(sql = "update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id)")
@SQLDelete(sql = "delete from receipt where id=? and tenant_id=coalesce(?,tenant_id)")
public class Receipt {

    @Id
    public Long id;

    @TenantId
    @Column(name = "tenant_id", nullable = false)
    public String tenant;

    public String memo;
The scenario (method customSqlGetsATenantParameter) runs with rls_enabled=false so that only this SQL stands between tenants. Output (05-custom-sql-tenant-parameter.txt):
rls_enabled=false, so only the SQL in @SQLUpdate and @SQLDelete stands between tenants.
tenantA edits its own receipt:
  update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id)  [a-edited, 1, tenantA]
root edits tenantB's receipt:
  update receipt set memo=? where id=? and tenant_id=coalesce(?,tenant_id)  [b-edited-by-root, 2, null]
tenantA tries to delete tenantB's receipt through a reference:
  -> rejected: ObjectNotFoundException: No row with the given identifier exists for entity [com.ankurm.tenant.Receipt with id '2']
  tenantB's receipt still exists: true
tenantA deletes its own receipt:
  delete from receipt where id=? and tenant_id=coalesce(?,tenant_id)  [1, tenantA]
root deletes tenantB's receipt:
  delete from receipt where id=? and tenant_id=coalesce(?,tenant_id)  [2, null]
The bound values are the proof: the last parameter is tenantA for a normal tenant and null for the root tenant. One honest detail: when tenantA tried to delete tenantB’s receipt through a reference, Hibernate raised ObjectNotFoundException and never sent a DELETE. The tenant filter hid the row at load time, so in that attempt it was the filter that stopped it, not the SQL predicate. The predicate is the backstop for the paths where the row is already known. Going deeper
  • The @SQLUpdate and @SQLDelete Javadoc in the CR2 sources describes the tenant parameter, including the case where the tenant id is part of the primary key

Run it yourself

Setup and commands You need JDK 25, Maven and a PostgreSQL 16 server you can create roles on. setup-postgres.sh creates the role and database, and run-all.sh runs the suite and prints every transcript. The tests read PG_URL, PG_USER and PG_PASSWORD and default to jdbc:postgresql://localhost:5433/tenantdemo as app/app. Scenario 03 also connects as postgres with an empty password for the superuser comparison, so on your own server either allow that locally or edit those two lines in RlsSafeModeTest.java.
PGHOST=localhost PGPORT=5432 PGUSER=postgres ./scripts/setup-postgres.sh
PG_URL=jdbc:postgresql://localhost:5432/tenantdemo ./scripts/run-all.sh
A run takes about ten seconds once Maven has its dependencies. The two pieces of test infrastructure worth reading are Lab.java, which boots a SessionFactory with safe mode and RLS toggled, and SqlRecorder.java, a JDBC wrapper that records each statement with its bound values.

Should you adopt this now?

My honest take. Do not ship production on 8.0.0.CR2; both settings are incubating and the project warns the 8.0 line may change. Do trial them on a branch, because both are cheap to try. Safe mode is one property plus a FunctionContributor for the functions you really use, and its failure mode is loud: a SemanticException at query parse time. RLS is the bigger decision: it only helps if the application role is not a superuser and does not have BYPASSRLS, it depends on a session variable that anyone with the credentials can change, and the generated DDL only runs when Hibernate creates the schema, so a migration-tool setup (Flyway, Liquibase) needs the same enable, force and create policy statements in your migrations. I did not test that route. I also did not test other databases, connection pools, Spring Boot integration, performance, or what a policy costs on large tables. If you need hard isolation between customers rather than a safety net, schema-per-tenant or database-per-tenant is still the stronger answer.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.