diff --git a/README.md b/README.md
index 13d940e..b269c06 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Runnable companion to the ankurm.com article on `EntityAgent` and stateless sess
Every number in the article comes from a file in [`output/`](output), and each of those files is
written by a test that asserts the same numbers, so a figure that stops being true fails the build.
-> Other module: [`jakarta-data/`](jakarta-data) holds the Jakarta Data repositories vs Spring Data JPA demo; [`flush-ordering/`](flush-ordering) the flush-queue demo.
+> Other module: [`jakarta-data/`](jakarta-data) holds the Jakarta Data repositories vs Spring Data JPA demo; [`flush-ordering/`](flush-ordering) the flush-queue demo; [`rls-safe-mode/`](rls-safe-mode) HQL safe mode and PostgreSQL row-level security for `@TenantId` (CR2, PostgreSQL 16).
## Versions tested
diff --git a/rls-safe-mode/README.md b/rls-safe-mode/README.md
new file mode 100644
index 0000000..cb5ee7c
--- /dev/null
+++ b/rls-safe-mode/README.md
@@ -0,0 +1,32 @@
+# Hibernate 8 safe mode for HQL, and PostgreSQL row-level security for multi-tenancy
+
+Runnable companion to the ankurm.com post on `hibernate.query.safe_mode_enabled` and Hibernate 8's generated
+PostgreSQL row-level-security policy for `@TenantId`. Every figure in the post comes from a file in
+[`output/`](output); each file is written by a test that asserts the same facts, so a claim that stops being true
+fails the build.
+
+Tested on Hibernate ORM 8.0.0.CR2 (release candidate, 24 Nov 2026), Jakarta Persistence 4.0.0-M8 (resolved
+transitively), PostgreSQL 16.15, pgjdbc 42.7.15, Temurin 25.0.5.1, JUnit 6.1.3, Maven 3.9.11.
+Both features are marked `@Incubating(since = "8.0")` in the CR2 sources. Behaviour may change before GA.
+
+ ./scripts/setup-postgres.sh # once: role "app" (no superuser, no BYPASSRLS) and database "tenantdemo"
+ ./scripts/run-all.sh # runs the tests and prints output/*.txt
+
+| File | What it shows |
+|---|---|
+| `src/main/java/com/ankurm/tenant/Invoice.java` | `@TenantId` entity |
+| `src/main/java/com/ankurm/tenant/Receipt.java` | `@SQLUpdate` / `@SQLDelete` with the extra tenant parameter |
+| `src/main/java/com/ankurm/tenant/TenantContext.java` | thread-bound tenant resolver, `admin` is the root tenant |
+| `src/main/java/com/ankurm/tenant/AppFunctions.java` | `FunctionContributor`: the safe-mode allow-list |
+| `src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor` | registers the contributor |
+| `src/test/java/com/ankurm/tenant/Lab.java` | boots a SessionFactory with safe mode and RLS toggled |
+| `src/test/java/com/ankurm/tenant/SqlRecorder.java` | JDBC wrapper that records SQL with bound values |
+| `src/test/java/com/ankurm/tenant/RlsSafeModeTest.java` | the five scenarios |
+
+| Output | Scenario |
+|---|---|
+| `output/01-safe-mode.txt` | nine HQL and Criteria calls, safe mode off and on |
+| `output/02-generated-rls-policy.txt`, `02b-rls-disabled.txt` | the policy Hibernate generated; nothing generated with `rls_enabled=false` |
+| `output/03-isolation.txt` | HQL, native SQL, raw JDBC, superuser, root tenant, no tenant |
+| `output/04-function-moves-tenant.txt` | a `set_config()` call from HQL moves the tenant |
+| `output/05-custom-sql-tenant-parameter.txt` | the tenant parameter in `@SQLUpdate` and `@SQLDelete` |
diff --git a/rls-safe-mode/output/01-safe-mode.txt b/rls-safe-mode/output/01-safe-mode.txt
new file mode 100644
index 0000000..c9d44e0
--- /dev/null
+++ b/rls-safe-mode/output/01-safe-mode.txt
@@ -0,0 +1,22 @@
+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 [sql] 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 [sql] is not allowed in safe mode
+ translate() built in on PostgreSQL ok: [xlice, bob]
+
diff --git a/rls-safe-mode/output/02-generated-rls-policy.txt b/rls-safe-mode/output/02-generated-rls-policy.txt
new file mode 100644
index 0000000..5fbf4a1
--- /dev/null
+++ b/rls-safe-mode/output/02-generated-rls-policy.txt
@@ -0,0 +1,11 @@
+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))
+ table=receipt 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))
diff --git a/rls-safe-mode/output/02b-rls-disabled.txt b/rls-safe-mode/output/02b-rls-disabled.txt
new file mode 100644
index 0000000..c2e6d5f
--- /dev/null
+++ b/rls-safe-mode/output/02b-rls-disabled.txt
@@ -0,0 +1,2 @@
+hibernate.multi_tenant.rls_enabled=false
+ policies=0 tables with row security=0
diff --git a/rls-safe-mode/output/03-isolation.txt b/rls-safe-mode/output/03-isolation.txt
new file mode 100644
index 0000000..97a4fc4
--- /dev/null
+++ b/rls-safe-mode/output/03-isolation.txt
@@ -0,0 +1,20 @@
+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
diff --git a/rls-safe-mode/output/04-function-moves-tenant.txt b/rls-safe-mode/output/04-function-moves-tenant.txt
new file mode 100644
index 0000000..035c22d
--- /dev/null
+++ b/rls-safe-mode/output/04-function-moves-tenant.txt
@@ -0,0 +1,8 @@
+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
+
diff --git a/rls-safe-mode/output/05-custom-sql-tenant-parameter.txt b/rls-safe-mode/output/05-custom-sql-tenant-parameter.txt
new file mode 100644
index 0000000..ad5cac1
--- /dev/null
+++ b/rls-safe-mode/output/05-custom-sql-tenant-parameter.txt
@@ -0,0 +1,12 @@
+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]
diff --git a/rls-safe-mode/pom.xml b/rls-safe-mode/pom.xml
new file mode 100644
index 0000000..b5fcb83
--- /dev/null
+++ b/rls-safe-mode/pom.xml
@@ -0,0 +1,51 @@
+
+
+ 4.0.0
+ com.ankurm
+ hibernate8-rls-safe-mode
+ 1.0.0
+ Hibernate 8 safe mode for HQL and PostgreSQL row-level security
+
+
+ 25
+ UTF-8
+ 8.0.0.CR2
+ 42.7.15
+ 6.1.3
+
+
+
+
+ org.hibernate.orm
+ hibernate-core
+ ${hibernate.version}
+
+
+ org.postgresql
+ postgresql
+ ${postgresql.version}
+
+
+ org.slf4j
+ slf4j-simple
+ 2.0.17
+
+
+ org.junit.jupiter
+ junit-jupiter
+ ${junit.version}
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.5.4
+
+
+
+
diff --git a/rls-safe-mode/scripts/run-all.sh b/rls-safe-mode/scripts/run-all.sh
new file mode 100755
index 0000000..9e5ce28
--- /dev/null
+++ b/rls-safe-mode/scripts/run-all.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Runs the whole suite and prints the transcripts it wrote to output/. Needs JDK 25, Maven and PostgreSQL 16+.
+# Override the connection with PG_URL, PG_USER, PG_PASSWORD (default jdbc:postgresql://localhost:5433/tenantdemo, app/app).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+mvn -B -q test
+for f in output/*.txt; do
+ echo "##### $f"
+ cat "$f"
+ echo
+done
diff --git a/rls-safe-mode/scripts/setup-postgres.sh b/rls-safe-mode/scripts/setup-postgres.sh
new file mode 100755
index 0000000..e7f9b6e
--- /dev/null
+++ b/rls-safe-mode/scripts/setup-postgres.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Creates the role and database the tests expect on a PostgreSQL you already run.
+# The application role must NOT be a superuser and must NOT have BYPASSRLS, or row-level security is skipped.
+# Usage: PGHOST=localhost PGPORT=5432 PGUSER=postgres ./scripts/setup-postgres.sh
+set -euo pipefail
+psql -v ON_ERROR_STOP=1 -c "create role app login password 'app' nosuperuser nobypassrls"
+psql -v ON_ERROR_STOP=1 -c "create database tenantdemo owner app"
+echo "Done. Tests connect to \${PG_URL:-jdbc:postgresql://localhost:5433/tenantdemo} as app/app."
+echo "The superuser comparison in 03-isolation connects as 'postgres' with an empty password (trust auth)."
diff --git a/rls-safe-mode/src/main/java/com/ankurm/tenant/AppFunctions.java b/rls-safe-mode/src/main/java/com/ankurm/tenant/AppFunctions.java
new file mode 100644
index 0000000..fdaea48
--- /dev/null
+++ b/rls-safe-mode/src/main/java/com/ankurm/tenant/AppFunctions.java
@@ -0,0 +1,23 @@
+package com.ankurm.tenant;
+
+import org.hibernate.boot.model.FunctionContributions;
+import org.hibernate.boot.model.FunctionContributor;
+import org.hibernate.type.StandardBasicTypes;
+
+/**
+ * The allow-list. With {@code hibernate.query.safe_mode_enabled=true} HQL may only call functions the
+ * dialect or a contributor registered. This contributor registers PostgreSQL's {@code initcap} and
+ * nothing else. It is discovered through META-INF/services.
+ */
+public class AppFunctions implements FunctionContributor {
+
+ @Override
+ public void contributeFunctions(FunctionContributions contributions) {
+ var string = contributions.getTypeConfiguration().getBasicTypeRegistry().resolve(StandardBasicTypes.STRING);
+ contributions.getFunctionRegistry()
+ .namedDescriptorBuilder("initcap")
+ .setExactArgumentCount(1)
+ .setInvariantType(string)
+ .register();
+ }
+}
diff --git a/rls-safe-mode/src/main/java/com/ankurm/tenant/Invoice.java b/rls-safe-mode/src/main/java/com/ankurm/tenant/Invoice.java
new file mode 100644
index 0000000..f4dbf92
--- /dev/null
+++ b/rls-safe-mode/src/main/java/com/ankurm/tenant/Invoice.java
@@ -0,0 +1,38 @@
+package com.ankurm.tenant;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import org.hibernate.annotations.TenantId;
+
+/**
+ * A tenant-owned row. {@code @TenantId} makes Hibernate (1) add {@code tenant_id = ?} to every HQL
+ * query and (2) in Hibernate 8, generate a PostgreSQL row-level-security policy on the table.
+ */
+@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;
+
+ public Invoice() {
+ }
+
+ public Invoice(String customer, int cents) {
+ this.customer = customer;
+ this.cents = cents;
+ }
+}
diff --git a/rls-safe-mode/src/main/java/com/ankurm/tenant/Receipt.java b/rls-safe-mode/src/main/java/com/ankurm/tenant/Receipt.java
new file mode 100644
index 0000000..031244a
--- /dev/null
+++ b/rls-safe-mode/src/main/java/com/ankurm/tenant/Receipt.java
@@ -0,0 +1,38 @@
+package com.ankurm.tenant;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import org.hibernate.annotations.SQLDelete;
+import org.hibernate.annotations.SQLUpdate;
+import org.hibernate.annotations.TenantId;
+
+/**
+ * Custom SQL for update and delete. Hibernate runs the SQL as written and adds no tenant predicate, so
+ * the statement must carry one. Hibernate 8 lets it declare one extra trailing {@code ?} that is bound
+ * to the session tenant (or to null for a root tenant).
+ */
+@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;
+
+ public Receipt() {
+ }
+
+ public Receipt(Long id, String memo) {
+ this.id = id;
+ this.memo = memo;
+ }
+}
diff --git a/rls-safe-mode/src/main/java/com/ankurm/tenant/TenantContext.java b/rls-safe-mode/src/main/java/com/ankurm/tenant/TenantContext.java
new file mode 100644
index 0000000..151fda1
--- /dev/null
+++ b/rls-safe-mode/src/main/java/com/ankurm/tenant/TenantContext.java
@@ -0,0 +1,33 @@
+package com.ankurm.tenant;
+
+import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
+
+/** Thread-bound tenant. {@code "admin"} is the root tenant: it may see every tenant's rows. */
+public class TenantContext implements CurrentTenantIdentifierResolver {
+
+ public static final String ROOT = "admin";
+ private static final ThreadLocal CURRENT = new ThreadLocal<>();
+
+ public static void set(String tenant) {
+ CURRENT.set(tenant);
+ }
+
+ public static void clear() {
+ CURRENT.remove();
+ }
+
+ @Override
+ public String resolveCurrentTenantIdentifier() {
+ return CURRENT.get();
+ }
+
+ @Override
+ public boolean validateExistingCurrentSessions() {
+ return false;
+ }
+
+ @Override
+ public boolean isRoot(String tenantId) {
+ return ROOT.equals(tenantId);
+ }
+}
diff --git a/rls-safe-mode/src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor b/rls-safe-mode/src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor
new file mode 100644
index 0000000..f2485a4
--- /dev/null
+++ b/rls-safe-mode/src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor
@@ -0,0 +1 @@
+com.ankurm.tenant.AppFunctions
diff --git a/rls-safe-mode/src/test/java/com/ankurm/tenant/Lab.java b/rls-safe-mode/src/test/java/com/ankurm/tenant/Lab.java
new file mode 100644
index 0000000..8a17ae7
--- /dev/null
+++ b/rls-safe-mode/src/test/java/com/ankurm/tenant/Lab.java
@@ -0,0 +1,66 @@
+package com.ankurm.tenant;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.jpa.HibernatePersistenceConfiguration;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+/** Boots a Hibernate 8 SessionFactory on a real PostgreSQL with safe mode and RLS toggled per test. */
+final class Lab implements AutoCloseable {
+
+ final SessionFactory sf;
+
+ Lab(boolean safeMode, boolean rls) {
+ 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");
+ this.sf = cfg.createEntityManagerFactory().unwrap(SessionFactory.class);
+ SqlRecorder.LOG.clear();
+ }
+
+ /** Runs work in one transaction as the given tenant. */
+ void as(String tenant, Consumer work) {
+ TenantContext.set(tenant);
+ try {
+ sf.inTransaction(work);
+ } finally {
+ TenantContext.clear();
+ }
+ }
+
+ T asReturning(String tenant, Function work) {
+ TenantContext.set(tenant);
+ try {
+ return sf.fromTransaction(work);
+ } finally {
+ TenantContext.clear();
+ }
+ }
+
+ /** SQL executed since the last call, then forgets it. */
+ List drain() {
+ List copy = List.copyOf(SqlRecorder.LOG);
+ SqlRecorder.LOG.clear();
+ return copy;
+ }
+
+ /** A plain JDBC connection that bypasses Hibernate entirely. */
+ static Connection raw(String user, String password) throws SQLException {
+ return DriverManager.getConnection(SqlRecorder.URL, user, password);
+ }
+
+ @Override
+ public void close() {
+ sf.close();
+ }
+}
diff --git a/rls-safe-mode/src/test/java/com/ankurm/tenant/RlsSafeModeTest.java b/rls-safe-mode/src/test/java/com/ankurm/tenant/RlsSafeModeTest.java
new file mode 100644
index 0000000..8e4cb07
--- /dev/null
+++ b/rls-safe-mode/src/test/java/com/ankurm/tenant/RlsSafeModeTest.java
@@ -0,0 +1,307 @@
+package com.ankurm.tenant;
+
+import jakarta.persistence.criteria.CriteriaBuilder;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.query.criteria.HibernateCriteriaBuilder;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Each test writes output/NN-name.txt and asserts the same facts the post quotes, so a figure that
+ * stops being true fails the build. Needs PostgreSQL: see ../README.md.
+ */
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class RlsSafeModeTest {
+
+ static void seed(Lab lab) {
+ lab.as("tenantA", s -> {
+ s.persist(new Invoice("alice", 1000));
+ s.persist(new Invoice("bob", 2500));
+ });
+ lab.as("tenantB", s -> s.persist(new Invoice("zed", 9900)));
+ lab.drain();
+ }
+
+ /** "ok: ..." or "rejected: ExceptionSimpleName: first line of the message". */
+ static String attempt(Callable