Skip to main content

@Formula, @Filter and @SQLRestriction in Hibernate 7: Computed and Filtered Data

What @Formula, @SQLRestriction and @Filter actually add to the SQL in Hibernate 7.4.17, shown with captured SQL: formula staleness and the unqualified-column trap, the filter that skips find-by-id and collections, applyToLoadByKey, an autoEnabled tenant filter that leaks, and the removed @Where.

You have a table where “the row” is not the whole story. An invoice needs its total, but the total is a sum over other rows. A task list must never show archived tasks. A report must only show rows above some priority, but only when someone asks. Hibernate has three annotations for exactly this — @Formula, @SQLRestriction and @Filter — and they look so alike that people reach for the wrong one, or assume one does the other’s job. They do not. Each one adds a different piece of SQL, in a different place, under different conditions. This article runs all three against a real database and shows the SQL Hibernate actually prepared, because the useful facts are all in the gaps: the lookup that ignores your filter, the collection that is not filtered, the value that goes stale, and the annotation (@Where) that no longer compiles.
Versions tested. Hibernate ORM 7.4.17.Final (newest 7.x GA in maven-metadata.xml on 2026-11-26), Jakarta Persistence 3.2.0, H2 2.4.240, JUnit 6.0.3, Java 25 (Temurin 25.0.5.1 LTS). Plain Hibernate, no Spring. Every SQL line and result below is quoted from a committed transcript produced by the test suite in hibernate-demo/formula-filter.

Three annotations, three different places in the SQL

Before any code, fix one mental model: when you load an entity, Hibernate writes a SELECT for you. These annotations let you reach into that statement. @Formula adds something to the select list. @SQLRestriction and @Filter add something to the WHERE clause — the first permanently, the second only when a session asks for it.
Each annotation edits one part of the SQL Hibernate writes for you select t.id, t.title, (sub-select …) from task t where archived = false and priority >= ? @Formula Adds an expression to the SELECT list. Read-only. Always on. @SQLRestriction Adds a fixed condition to WHERE. No parameters. Always on. @Filter Adds a parameterised condition to WHERE. Off until a session enables it. Formula changes what you read. The other two change which rows you can read at all. Everything in this article is a question of where that extra SQL is, and is not, added.
The diagram is the whole article in one picture. Formula changes what you read for each row; the other two change which rows you can read at all. When something surprising happens later, ask which of the two places the SQL is missing from.
@Formula@SQLRestriction@Filter
Where it goesSELECT listWHEREWHERE
Always on?YesYesNo — enabled per session
Parameters?NoNoYes
Writes?Never writtenAlso on bulk update/deleteAlso on bulk update/delete
Going deeper: what is not in this list Two neighbouring tools are deliberately left out so the page stays on one question. @SoftDelete and @SQLDelete are about deleting rows without removing them; they are covered with the same @SQLRestriction in Soft Delete in Hibernate 7. @TenantId and schema-per-tenant are the structural way to isolate tenants and are compared in Multi-Tenancy with Hibernate 7 and Spring Boot 4; the tenant filter near the end of this article is the lightweight alternative and shows where it leaks.

Going deeper

@Formula: a column that is not a column

Start with the smallest example. A person has a first name and a last name stored separately, and you want fullName on the entity without a third column that can drift out of sync. The mapping is in Person.java:
/** Smallest possible @Formula: a value computed by the database on every SELECT, never stored. */
@Entity
@Table(name = "person")
public class Person {

	@Id
	Long id;

	@Column(name = "first_name")
	String firstName;

	@Column(name = "last_name")
	String lastName;

	/** Not a column. Hibernate pastes this SQL fragment into the SELECT list. */
	@Formula("first_name || ' ' || last_name")
	String fullName;
Hibernate does not create a full_name column, and it does not insert or update one. It pastes the SQL fragment into every SELECT for Person. Here is what the test in T01_FormulaTest.java saw (transcript: output/01-formula.txt):
-- columns of table person (information_schema)
   sql> select column_name from information_schema.columns where table_name = 'PERSON' order by column_name
   => [FIRST_NAME, ID, LAST_NAME]
-- find(Person, 1).getFullName()
   sql> select p1_0.id,p1_0.first_name,p1_0.first_name || ' ' || p1_0.last_name,p1_0.last_name from person p1_0 where p1_0.id=?
   => Asha Kulkarni
Read the second statement closely: the fragment first_name || ' ' || last_name became p1_0.first_name || ' ' || p1_0.last_name. Hibernate rewrote your bare column names so they point at the Person table in this query. You wrote it once, and it keeps working however the entity ends up aliased. Keep that rewriting in mind — it is the source of the one real trap, two sections down.
Intermediate: a correlated sub-select, repeated in WHERE and ORDER BY A formula can be any SQL expression, including a sub-select. Invoice.java derives total and lineCount from child rows:
	@Formula("(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = id)")
	BigDecimal total;

	@Formula("(select count(*) from invoice_line l where l.invoice_id = id)")
	int lineCount;
Loading an invoice computes both in the same round trip — one statement, no extra query:
-- find(Invoice, 1): total and lineCount
   sql> select i1_0.id,i1_0.customer,(select count(*) from invoice_line l where l.invoice_id = i1_0.id),(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) from invoice i1_0 where i1_0.id=?
   => total=130.00 lineCount=2
You can use the property in HQL as if it were a column. Hibernate does not reference a column here, because there is none; it copies the whole fragment into each place you mention the property. The test counted three copies of the sum sub-select in this one statement (select list, WHERE, ORDER BY):
-- from Invoice i where i.total > 40 order by i.total desc
   sql> select i1_0.id,i1_0.customer,(select count(*) from invoice_line l where l.invoice_id = i1_0.id),(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) from invoice i1_0 where (select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id)>40 order by (select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) desc
   => [Acme, Globex]
   (the total sub-select appears 3 times in that one statement)
That is correct and often fine, but it means a formula is a per-row cost on every read. A projection that does not mention the property does not pay it — the first statement below has no sub-select at all (output in output/01-formula.txt):
-- select i.id, i.customer from Invoice i
   sql> select i1_0.id,i1_0.customer from invoice i1_0
   => 3
-- select i.id, i.customer, i.total from Invoice i
   sql> select i1_0.id,i1_0.customer,(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) from invoice i1_0
   => 3

A @Formula value is a snapshot, and you cannot write to it

Because the value arrives with the row, it is only as fresh as that read. Load an invoice, add a line, flush — the database total moves and the entity in memory does not.
A @Formula value is a snapshot taken when the row was read find(Invoice)total = 50.00(database: 50.00) persist(line) + flushdatabase: 150.00 getTotal()still 50.00(stale) refresh(invoice)total = 150.00 Flushing writes the new line, but Hibernate has no reason to re-run the sub-select for an entity it already holds. Only refresh(), a fresh session, or a query that re-reads the row gives you the new number.
The timeline shows the gap: flushing sends the INSERT but nothing re-reads the entity. The test ran exactly that sequence (output/01-formula.txt):
-- load Globex, add a 100.00 line, flush, read total, refresh, read total
   sql> select i1_0.id,i1_0.customer,(select count(*) from invoice_line l where l.invoice_id = i1_0.id),(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) from invoice i1_0 where i1_0.id=?
   sql> insert into invoice_line (invoice_id,qty,unit_price,id) values (?,?,?,default)
   sql> select i1_0.id,i1_0.customer,(select count(*) from invoice_line l where l.invoice_id = i1_0.id),(select coalesce(sum(l.qty * l.unit_price), 0) from invoice_line l where l.invoice_id = i1_0.id) from invoice i1_0 where i1_0.id=?
   => before=50.00 afterFlush=50.00 afterRefresh=150.00
afterFlush=50.00 is the stale value; afterRefresh=150.00 is what refresh() fetched with a second SELECT. If a screen shows a total right after you add a line, refresh first. The same read-only rule means assigning to the property does nothing to the database (same transcript, output/01-formula.txt):
-- setFullName("HACK"); setLastName("Patil-Rao"); flush
   sql> select p1_0.id,p1_0.first_name,p1_0.first_name || ' ' || p1_0.last_name,p1_0.last_name from person p1_0 where p1_0.id=?
   sql> update person set first_name=?,last_name=? where id=?
   => full name in memory is now HACK
-- fresh session: find(Person, 2).getFullName()  (recomputed from the new last_name; HACK is gone)
   sql> select p1_0.id,p1_0.first_name,p1_0.first_name || ' ' || p1_0.last_name,p1_0.last_name from person p1_0 where p1_0.id=?
   => Ravi Patil-Rao
The UPDATE carries only first_name and last_name. The in-memory HACK vanished with the session, and the next read recomputed the name from the changed last name. Treat a formula property as a getter backed by SQL, not a field.
The one real trap. Inside a sub-select, a column name with no table alias is rewritten to the outer table’s alias. In Invoice the fragment is sum(l.qty * l.unit_price) with an l. on every inner column. Drop the prefix and Hibernate qualifies qty with the invoice alias instead of the line alias. H2 then reports that column as not found on the invoice alias — see the next block. Qualify every column of every inner table.
The deliberately broken mapping is BrokenFormula.java and its transcript is output/02-formula-unqualified.txt:
-- find(BrokenFormula, 1) with sum(qty * unit_price) and no l. prefix
   sql> select bf1_0.id,bf1_0.customer,(select coalesce(sum(bf1_0.qty * bf1_0.unit_price), 0) from invoice_line l where l.invoice_id = bf1_0.id) from invoice bf1_0 where bf1_0.id=?
   => SQLGrammarException: Could not prepare statement [Column "BF1_0.QTY" not found; SQL statement:
Compare sum(bf1_0.qty * bf1_0.unit_price) with the working sum(l.qty * l.unit_price) earlier: same intent, but bf1_0 is the invoice, and the invoice has no qty.
Intermediate: portability, and why the outer column id needed no prefix Notice that l.invoice_id = id in the working mapping has a bare id, and that is rewritten to i1_0.id — which is exactly what you wanted. The rule is consistent: bare columns belong to the entity that owns the formula; columns of anything you join or sub-select need their own alias. That is why the example works and the broken one does not. A formula is raw SQL, so it is as portable as the SQL inside it. || for concatenation works on H2 and PostgreSQL but not everywhere; date arithmetic and string functions vary much more. If you target several databases, the 7.4.17 jar ships a dialect-aware override, @DialectOverride.Formula (I saw it listed in the jar); this module does not exercise it, so treat it as a pointer rather than a tested recipe.

Going deeper

@SQLRestriction: a WHERE clause that is always there

Now the rows. Suppose tasks can be archived and nobody should ever see an archived one through the application. @SQLRestriction takes a SQL condition and appends it to every read of the entity. Task.java:
@Entity
@Table(name = "task")
@SQLRestriction("archived = false")
@FilterDef(name = "minPriority", defaultCondition = "priority >= :level",
		parameters = @ParamDef(name = "level", type = Integer.class))
@Filter(name = "minPriority")
public class Task {
(The @FilterDef and @Filter lines belong to the next section; ignore them for now.) Task 3 in the test data is archived. The transcript output/03-sql-restriction.txt shows that Hibernate adds the condition to a query, to a lookup by primary key, to a lazy collection and to a join fetch:
-- from Task
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where (t1_0.archived = false)
   => [Backfill, Fix flaky test, Rotate logs, Upgrade JDK]
-- find(Task, 3): the archived row, by primary key
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.id=? and (t1_0.archived = false)
   => null
-- find(Department, 1).getTasks()
   sql> select d1_0.id,d1_0.name from department d1_0 where d1_0.id=?
   sql> select t1_0.department_id,t1_0.id,t1_0.archived,t1_0.priority,t1_0.title from task t1_0 where t1_0.department_id=? and (t1_0.archived = false)
   => [Fix flaky test, Rotate logs, Upgrade JDK]
-- select d from Department d join fetch d.tasks where d.id = 1
   sql> select d1_0.id,d1_0.name,t1_0.department_id,t1_0.id,t1_0.archived,t1_0.priority,t1_0.title from department d1_0 join task t1_0 on d1_0.id=t1_0.department_id and (t1_0.archived = false) where d1_0.id=1
   => [Fix flaky test, Rotate logs, Upgrade JDK]
The primary-key lookup is the one to notice: asking for an archived task by id returns null, as if it did not exist. For a restriction that is what you want — it cannot be bypassed by a different way of asking. The same fragment appears on bulk HQL (output/03-sql-restriction.txt):
-- update Task set priority = priority + 10
   sql> update task t1_0 set priority=(t1_0.priority+10) where (t1_0.archived = false)
   => 4
Four rows were updated, not five, because the archived row is invisible to the statement too. The one place it does not reach is native SQL, which Hibernate never rewrites (output/03-sql-restriction.txt):
-- createNativeQuery("select count(*) from task")
   sql> select count(*) from task
   => 5
The dangling reference. If another entity points at a restricted row, the reference breaks. A Note that points at archived task 3 loads fine, but touching its task raises ObjectNotFoundException (Hibernate’s own, not a jakarta.persistence one), because the lookup for task 3 now has archived = false in it and finds nothing. Note 2, pointing at a live task, works. If hidden rows can still be referenced, either null the references when you hide the row or accept the exception and handle it.
-- find(Note, 1).getTask().getTitle()
   sql> select n1_0.id,n1_0.task_id,n1_0.text from note n1_0 where n1_0.id=?
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.id=? and (t1_0.archived = false)
   => ObjectNotFoundException: No row with the given identifier exists for entity [com.ankurm.formulafilter.Task with id '3']
-- find(Note, 2).getTask().getTitle() (points at a live Task)
   sql> select n1_0.id,n1_0.task_id,n1_0.text from note n1_0 where n1_0.id=?
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.id=? and (t1_0.archived = false)
   => Upgrade JDK
The entity for this is Note.java.
Intermediate: @Where is gone in Hibernate 7 If you are upgrading, you will meet @Where. It was the older spelling of @SQLRestriction and Hibernate 7 removed it; the 7.0 migration guide says to use @SQLRestriction (and @SQLJoinTableRestriction instead of @WhereJoinTable). The module keeps a mapping that uses it outside the Maven build (WhereRemoved.java) and a script (compile-broken.sh) that records the compiler’s own message in output/07-where-removed.txt:
# @Where on Hibernate 7.4.17.Final
# JDK javac 25.0.5.1
$ javac -cp <hibernate-core, jakarta.persistence-api> src/broken/WhereRemoved.java
src/broken/WhereRemoved.java:3: error: cannot find symbol
import org.hibernate.annotations.Where;
                                ^
  symbol:   class Where
  location: package org.hibernate.annotations
src/broken/WhereRemoved.java:7: error: cannot find symbol
@Where(clause = "archived = false")
 ^
  symbol: class Where
2 errors
The fix is a rename: @SQLRestriction("archived = false") takes the condition as value instead of clause. The wider upgrade is in Hibernate 5 to 7 Migration Guide and Cheat Sheet.

Going deeper

@Filter: the same idea, but you switch it on

Sometimes the condition depends on who is asking, or only applies to one screen. @Filter is a @SQLRestriction with two differences: it takes parameters, and it does nothing until a session enables it. You declare it once with @FilterDef, attach it to the entity with @Filter (both in the Task source above), then enable it for the session:
	static void on(Session s, int level) {
		s.enableFilter("minPriority").setParameter("level", level);
	}
From T04_FilterTest.java. With the filter defined but never enabled, nothing changes; once enabled it is ANDed with the permanent restriction. Transcript: output/04-filter.txt:
-- from Task (filter never enabled)
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where (t1_0.archived = false)
   => [Backfill, Fix flaky test, Rotate logs, Upgrade JDK]
-- enableFilter(level=3); from Task
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.priority >= ? and (t1_0.archived = false)
   => [Fix flaky test, Upgrade JDK]
The filter lives on the Session that enabled it, not on the SessionFactory. A second session opened by hand sees all four rows, while the one that enabled it sees two:
-- session A enables level=3; session B (opened by hand) queries
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.priority >= ? and (t1_0.archived = false)
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where (t1_0.archived = false)
   => sessionA=2 sessionB=4
In an application that means the code that opens a session (a request filter, a transaction hook) is the one place that must enable it — and the place that breaks if a code path opens a session another way. Leaving the parameter out fails at query time rather than silently (output/04-filter.txt):
-- enableFilter("minPriority") without setParameter; from Task
   (no SQL)
   => HibernateException: Filter parameter 'minPriority' has neither an argument nor a resolver
Intermediate: bulk statements and native SQL Hibernate applies an enabled filter to bulk HQL as well as to queries, so an update Task ... with the filter on touched only the two rows above the level. Native SQL is untouched, exactly as with @SQLRestriction (output/04-filter.txt):
-- enableFilter(level=3); update Task set priority = priority + 10
   sql> update task t1_0 set priority=(t1_0.priority+10) where t1_0.priority >= ? and (t1_0.archived = false)
   => 2
-- enableFilter(level=3); native select count(*) from task
   sql> select count(*) from task
   => 5
The count of 2 for the update is an assertion in the test; if a Hibernate release changes that, the build fails and this article is wrong. For a filter that guards data (a tenant, a permission), that is behaviour worth pinning in your own tests.

Going deeper

Where a filter does not apply

This is the section that earns the article its length. A filter is easy to switch on and easy to believe in; the transcripts show three places where it quietly does not apply.
Where a switched-on @Filter does and does not reach (Task, level = 3) from Task (HQL) applied find(Task, id) skipped dept.getTasks() skipped dept.getFilteredTasks() applied update Task set … (bulk HQL) applied native select … from task skipped The two skipped Hibernate paths are the ones people assume are covered: a primary-key lookup, and a collection on a parent entity. find-by-id can be fixed with applyToLoadByKey; the collection needs its own @Filter. A collection that is already initialised when you enable the filter is never re-filtered either. Native SQL is outside Hibernate’s rewriting entirely, for filters and for @SQLRestriction alike.
Green boxes are paths that carry the condition, red boxes are paths that do not. Everything in the red column is a legitimate way to read the same rows, so a filter used as a security boundary needs each one handled on purpose.

1. A lookup by primary key

With the filter on, find(Task, 2) returned the priority-1 task the filter was supposed to hide. Compare the SQL with the query above: the priority condition is simply not there; only the permanent @SQLRestriction is.
-- enableFilter(level=3); find(Task, 2)  [Rotate logs has priority 1]
   sql> select t1_0.id,t1_0.archived,t1_0.department_id,t1_0.priority,t1_0.title from task t1_0 where t1_0.id=? and (t1_0.archived = false)
   => Rotate logs priority=1
By default Hibernate does not apply a filter to a lookup by key; the @FilterDef has to say applyToLoadByKey = true. Ticket.java sets it:
@FilterDef(name = "ticketPriority", defaultCondition = "priority >= :level", applyToLoadByKey = true,
		parameters = @ParamDef(name = "level", type = Integer.class))
@Filter(name = "ticketPriority")
The result with the same level of 3 (transcript output/05-apply-to-load-by-key.txt): ticket 1 (priority 1) is now null, ticket 2 (priority 5) loads.
-- enableFilter(ticketPriority, level=3); find(Ticket, 1)  [priority 1]
   sql> select t1_0.id,t1_0.priority,t1_0.title from ticket t1_0 where t1_0.id=? and t1_0.priority >= ?
   => null
-- enableFilter(ticketPriority, level=3); find(Ticket, 2)  [priority 5]
   sql> select t1_0.id,t1_0.priority,t1_0.title from ticket t1_0 where t1_0.id=? and t1_0.priority >= ?
   => Payment fails

2. A collection of the filtered entity

Putting @Filter on Task does not filter department.getTasks(). The collection loads with the @SQLRestriction (that one is on the entity and always applies) but not with the filter. A collection needs its own @Filter on the field. Department.java maps the same rows twice to show both:
	@OneToMany(mappedBy = "department")
	List<Task> tasks = new ArrayList<>();
	/** The same rows as {@link #tasks}, but this collection carries its own @Filter: the entity-level one does not reach it. */
	@OneToMany(mappedBy = "department")
	@Filter(name = "minPriority")
	List<Task> filteredTasks = new ArrayList<>();
Both snippets are from Department.java; the results:
-- enableFilter(level=3); find(Department, 1).getTasks()  (collection has no @Filter)
   sql> select d1_0.id,d1_0.name from department d1_0 where d1_0.id=?
   sql> select t1_0.department_id,t1_0.id,t1_0.archived,t1_0.priority,t1_0.title from task t1_0 where t1_0.department_id=? and (t1_0.archived = false)
   => [Fix flaky test, Rotate logs, Upgrade JDK]
-- enableFilter(level=3); find(Department, 1).getFilteredTasks()  (collection has its own @Filter)
   sql> select d1_0.id,d1_0.name from department d1_0 where d1_0.id=?
   sql> select ft1_0.department_id,ft1_0.id,ft1_0.archived,ft1_0.priority,ft1_0.title from task ft1_0 where ft1_0.department_id=? and ft1_0.priority >= ? and (ft1_0.archived = false)
   => [Fix flaky test, Upgrade JDK]
Three tasks come back from the plain collection, two from the filtered one. A join fetch of the filtered collection carries the condition in its ON clause (see the join statement in output/04-filter.txt).

3. A collection that is already loaded

Enabling a filter does not retroactively filter a collection that has already been initialised. The test touches the filtered collection, then enables the filter, then reads it again:
-- getFilteredTasks().size() BEFORE enableFilter, then again AFTER
   sql> select d1_0.id,d1_0.name from department d1_0 where d1_0.id=?
   sql> select ft1_0.department_id,ft1_0.id,ft1_0.archived,ft1_0.priority,ft1_0.title from task ft1_0 where ft1_0.department_id=? and (ft1_0.archived = false)
   => before=3 after=3
before=3 after=3: the second read is the same in-memory list. If a request enables the filter after some earlier code already walked the association, the filter silently does nothing for that collection. Enable it first, at session open.
Intermediate: why the defaults are like this These are all consequences of one design: a filter is a condition added to statements Hibernate builds. A lookup by key and a lazy collection that is already filled are not statements anymore, or never were. Treat the three gaps as a checklist when you review code that depends on a filter: how is the row fetched, is that fetch a statement I control, and does the session enable the filter before anything touches it. Not tested here: the interaction with the second-level cache. If you cache filtered entities or collections, test that explicitly before trusting it; this module does not configure a cache.

Going deeper

Tenant filters: autoEnabled, and the one gap that leaks

The usual real-world use of a filter is “only my tenant’s rows”. Calling enableFilter in every session is exactly the kind of thing someone forgets, so @FilterDef has autoEnabled = true together with a parameter resolver — a Supplier Hibernate calls itself. Document.java:
@FilterDef(name = "tenant", defaultCondition = "tenant_id = :tenantId", autoEnabled = true,
		parameters = @ParamDef(name = "tenantId", type = Long.class, resolver = CurrentTenant.class))
@Filter(name = "tenant")
The resolver is the small CurrentTenant.java class (a stand-in for “whoever is logged in”). No session code calls enableFilter; switching the tenant changes the parameter for the next session (transcript output/06-auto-enabled.txt):
-- CurrentTenant=1; from Document
   sql> select d1_0.id,d1_0.tenant_id,d1_0.title from document d1_0 where d1_0.tenant_id = ? order by d1_0.id
   => [Q1 plan, Q2 plan]
-- CurrentTenant=2, new session; from Document
   sql> select d1_0.id,d1_0.tenant_id,d1_0.title from document d1_0 where d1_0.tenant_id = ? order by d1_0.id
   => [Other company plan]
Good. Now the gap from the previous section, in its most expensive form. This FilterDef does not set applyToLoadByKey, so a lookup by id for another tenant’s document works:
-- CurrentTenant=1; find(Document, 3)  [belongs to tenant 2]
   sql> select d1_0.id,d1_0.tenant_id,d1_0.title from document d1_0 where d1_0.id=?
   => Other company plan (tenant 2)
This is a data leak. With the tenant set to 1, find(Document, 3) returned a document that belongs to tenant 2 — the SQL has no tenant_id condition. Any endpoint that takes an id from the caller and calls find is now a cross-tenant read. The fix is one attribute.
Memo.java is the same definition with applyToLoadByKey = true:
@FilterDef(name = "memoTenant", defaultCondition = "tenant_id = :tenantId", autoEnabled = true, applyToLoadByKey = true,
		parameters = @ParamDef(name = "tenantId", type = Long.class, resolver = CurrentTenant.class))
@Filter(name = "memoTenant")
-- CurrentTenant=1; find(Memo, 2)  [belongs to tenant 2]
   sql> select m1_0.id,m1_0.tenant_id,m1_0.title from memo m1_0 where m1_0.id=? and m1_0.tenant_id = ?
   => null
-- CurrentTenant=1; find(Memo, 1)
   sql> select m1_0.id,m1_0.tenant_id,m1_0.title from memo m1_0 where m1_0.id=? and m1_0.tenant_id = ?
   => Memo A
The foreign memo is now null; the tenant’s own memo loads. Even then, remember the other red boxes in the diagram: native SQL and anything that bypasses Hibernate are not covered, so a filter is a convenience layer, not an authorisation system.
Intermediate: filter vs @TenantId vs schema-per-tenant A filter-based tenant guard is the cheapest to adopt and the easiest to get subtly wrong, as above. Hibernate’s @TenantId and the schema-per-tenant approach push isolation lower, at the cost of more setup. The comparison, with the failure modes reproduced, is in Multi-Tenancy with Hibernate 7 and Spring Boot 4. The test switches the tenant between sessions and each new session picks up the new value; it does not test switching the tenant in the middle of a session, so do not rely on that.

Going deeper

Which one should you use?

You want…UseWatch for
A derived value on the entity@FormulaStale after writes; qualify inner columns; cost on every load
Rows hidden always, for everyone@SQLRestrictionDangling references; native SQL bypasses it
Rows hidden depending on the caller or the screen@FilterSession-scoped; find-by-id; collections; already-loaded collections
A tenant guard with no per-session code@Filter with autoEnabled + applyToLoadByKeyStill not a security boundary
Should you even use these? Use @Formula for small, cheap expressions and not for aggregates over large child tables — a sub-select computed for every loaded row is a performance bug waiting for a list screen. For aggregates you read in lists, a projection or a database view is usually better. Use filters for convenience scoping, but if the filtered rows are confidential, enforce that in the database (row-level security, separate schemas) and treat the filter as a second line, because the gaps above are easy to open by accident.

Further reading

No Comments yet!

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