Add formula-filter module: @Formula, @Filter and @SQLRestriction in Hibernate 7.4.17.Final (generated SQL, @Formula staleness and unqualified-column trap, filter gaps for find-by-id and collections, applyToLoadByKey, autoEnabled tenant filter, removed @Where; H2)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3W3uHbHAmM3orhn7b
This commit is contained in:
Claude
2026-11-26 00:45:29 +05:30
parent bd0f33a306
commit ec6eda8650
32 changed files with 1147 additions and 0 deletions
+1
View File
@@ -354,3 +354,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo
| [`one-to-many`](one-to-many/) | `@OneToMany` in Hibernate 7: unidirectional join table vs `@JoinColumn` vs bidirectional `mappedBy`, the SQL each sends, why removing one child from a join-table `List` deletes and re-inserts the rest (and why a `mappedBy` List does not), the bidirectional sync helper, fetch defaults, N+1 fixes, `MultipleBagFetchException` and its three fixes, and the id-based `hashCode` trap; plain Hibernate on H2 (Hibernate `7.4.16.Final`) |
| [`n-plus-one-guard`](n-plus-one-guard/) | Detecting N+1 queries automatically: Hibernate Statistics vs datasource-proxy (what each counts and what each misses), five fixes with statement counts, and a JUnit 6 `@MaxSelects` guard that fails a test with the full SQL list; plain Hibernate on H2 (Hibernate `7.4.16.Final`, datasource-proxy `1.11.1`) |
| [`enums`](enums/) | Enum mapping in Hibernate 7: `ORDINAL` vs `STRING` vs PostgreSQL native enum vs `AttributeConverter` vs JPA 3.2 `@EnumeratedValue`, the DDL each creates, what release 2 reads and writes after a constant is inserted, appended or renamed, `hbm2ddl=update` limits and the migration each change needs; plain Hibernate on H2 and PostgreSQL 18 (Hibernate `7.4.17.Final`) |
| [`formula-filter`](formula-filter/) | `@Formula`, `@Filter` and `@SQLRestriction` in Hibernate 7: the SQL each one adds, `@Formula` staleness and the unqualified-column trap, where filters skip find-by-id, collections and loaded collections, `applyToLoadByKey`, `autoEnabled` tenant filters, and the removed `@Where`; plain Hibernate on H2 (Hibernate `7.4.17.Final`) |
+35
View File
@@ -0,0 +1,35 @@
# formula-filter
Companion module for the ankurm.com article **@Formula, @Filter and @SQLRestriction in Hibernate 7: Computed and Filtered Data**.
Every SQL statement, result and error message in the article comes from a test here; each test writes what it observed to `output/` and asserts the same facts.
Plain Hibernate on an in-memory H2: no Spring, no Docker, no database server.
## Versions
| Component | Version | Notes |
|---|---|---|
| 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` | in memory |
| JUnit / AssertJ | `6.0.3` / `3.27.7` | |
| Java | `25` (Temurin 25.0.5.1 LTS) | |
## Run
```bash
./scripts/run-all.sh # mvn clean test, then the compile-failure demo; regenerates everything in output/
```
## Tests and what they write
| Test | Output | Question it answers |
|---|---|---|
| `T01_FormulaTest.formula` | `output/01-formula.txt` | What SQL does `@Formula` add, where is it repeated, when does the value go stale, is it really read-only? |
| `T01_FormulaTest.unqualifiedColumnInsideSubselect` | `output/02-formula-unqualified.txt` | Why does a column inside a formula's sub-select fail with the *outer* table's alias? |
| `T03_SqlRestrictionTest` | `output/03-sql-restriction.txt` | Where does `@SQLRestriction` reach: find-by-id, collections, join fetch, bulk DML, native SQL, dangling references |
| `T04_FilterTest.filter` | `output/04-filter.txt` | Where does `@Filter` reach, and which places does it silently skip (find-by-id, collections, already-loaded collections) |
| `T04_FilterTest.applyToLoadByKey` | `output/05-apply-to-load-by-key.txt` | What does `applyToLoadByKey = true` change |
| `T06_AutoEnabledTest` | `output/06-auto-enabled.txt` | `autoEnabled` + a parameter resolver as a tenant filter, and the find-by-id gap |
| `scripts/compile-broken.sh` | `output/07-where-removed.txt` | The compiler error for `@Where`, which Hibernate 7 removed |
The mappings live in `src/main/java/com/ankurm/formulafilter/`: `Person` and `Invoice` (`@Formula`), `Task` / `Department` / `Ticket` (`@SQLRestriction`, `@Filter`), `Document` and `Memo` (`autoEnabled`). `src/broken/` is deliberately outside the Maven build.
+48
View File
@@ -0,0 +1,48 @@
# @Formula: a computed, read-only property (tables person, invoice, invoice_line)
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
== 1. A column-less property: no DDL, just a SQL fragment in the SELECT
-- 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
== 2. A correlated sub-select: computed on every load of the entity
-- 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
-- find(Invoice, 3): an invoice with no lines
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=?
=> 0
== 3. Use it in HQL: the fragment is pasted into WHERE and ORDER BY as well
-- 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)
== 4. The price of loading it: a projection that skips the property skips the sub-select
-- 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
== 5. Staleness: the value is read once, with the entity
-- 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
== 6. Read-only: assigning to the property sends nothing to the database
-- 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
@@ -0,0 +1,5 @@
# @Formula trap: an unqualified column inside a sub-select is aliased to the OUTER table
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
-- 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:
@@ -0,0 +1,37 @@
# @SQLRestriction("archived = false") on Task (task 3 'Old migration' is archived)
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
== 1. Everywhere Hibernate reads Task rows
-- 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]
== 2. Bulk HQL updates and deletes carry it too
-- update Task set priority = priority + 10
sql> update task t1_0 set priority=(t1_0.priority+10) where (t1_0.archived = false)
=> 4
== 3. Native SQL is not rewritten
-- createNativeQuery("select count(*) from task")
sql> select count(*) from task
=> 5
== 4. The dangling reference: a Note points at the archived Task
-- 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
+53
View File
@@ -0,0 +1,53 @@
# @Filter("minPriority": priority >= :level) on Task, @SQLRestriction(archived = false) also on
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
== 1. Defined but not enabled: no effect
-- 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]
== 2. Enabled for this session: it is ANDed with the @SQLRestriction
-- 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]
== 3. The primary-key lookup ignores it (applyToLoadByKey defaults to false)
-- 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
== 4. Collections: an @Filter on the entity does not reach a collection of that entity
-- 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]
-- 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
-- enableFilter(level=3); join fetch d.filteredTasks
sql> select d1_0.id,ft1_0.department_id,ft1_0.id,ft1_0.archived,ft1_0.priority,ft1_0.title,d1_0.name from department d1_0 join task ft1_0 on d1_0.id=ft1_0.department_id and ft1_0.priority >= ? and (ft1_0.archived = false) where d1_0.id=1
=> [Fix flaky test, Upgrade JDK]
== 5. Bulk HQL and native SQL
-- 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
== 6. Scope: one Session, not the SessionFactory
-- 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
== 7. Forgetting the parameter
-- enableFilter("minPriority") without setParameter; from Task
(no SQL)
=> HibernateException: Filter parameter 'minPriority' has neither an argument nor a resolver
@@ -0,0 +1,8 @@
# @FilterDef(applyToLoadByKey = true) on Ticket vs the default on Task
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
-- 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
+23
View File
@@ -0,0 +1,23 @@
# autoEnabled = true with resolver = CurrentTenant (a Supplier<Long>)
# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25
== 1. No enableFilter() call anywhere
-- 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]
== 2. The gap: find-by-id on an entity whose FilterDef lacks applyToLoadByKey
-- 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)
== 3. The fix: the same definition with applyToLoadByKey = true (entity Memo)
-- 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
@@ -0,0 +1,13 @@
# @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
+65
View File
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm</groupId>
<artifactId>formula-filter</artifactId>
<version>1.0.0</version>
<name>formula-filter</name>
<description>@Formula, @Filter and @SQLRestriction in Hibernate 7: computed and filtered data (plain Hibernate on H2)</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Newest 7.x GA in maven-metadata.xml on 2026-11-26 (8.0.0.CR1 is listed after it, but CR1 is not GA). -->
<hibernate.version>7.4.17.Final</hibernate.version>
<persistence.version>3.2.0</persistence.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>${persistence.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.4.240</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>6.0.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.27.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<argLine>-Xmx512m</argLine>
<systemPropertyVariables>
<h.version>${hibernate.version}</h.version>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Compiles src/broken/WhereRemoved.java (kept outside the Maven build) and records javac's own message in output/07-where-removed.txt.
set -uo pipefail
cd "$(dirname "$0")/.."
mvn -B -q dependency:build-classpath -Dmdep.outputFile=target/cp.txt -Dmdep.includeScope=compile >/dev/null 2>&1
mkdir -p target/broken output
{
echo "# @Where on Hibernate $(mvn -B -q help:evaluate -Dexpression=hibernate.version -DforceStdout 2>/dev/null | tail -1)"
echo "# JDK $(javac -version 2>&1 | grep -v Picked | tail -1)"
echo "\$ javac -cp <hibernate-core, jakarta.persistence-api> src/broken/WhereRemoved.java"
javac -proc:none -d target/broken -cp "$(cat target/cp.txt)" src/broken/WhereRemoved.java 2>&1 | grep -v -E '^Picked up'
} > output/07-where-removed.txt
cat output/07-where-removed.txt
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Regenerates every file under output/. Needs JDK 25 and Maven 3.9; no database server, no Docker.
# ./scripts/run-all.sh
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -B clean test
./scripts/compile-broken.sh >/dev/null || true
ls -1 output
@@ -0,0 +1,14 @@
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.hibernate.annotations.Where;
/** Compiles on Hibernate 6.x with a deprecation warning. On Hibernate 7 the annotation no longer exists. */
@Entity
@Where(clause = "archived = false")
class WhereRemoved {
@Id
Long id;
boolean archived;
}
@@ -0,0 +1,14 @@
package com.ankurm.formulafilter;
import java.util.function.Supplier;
/** Stand-in for "whoever is logged in": a filter parameter resolver Hibernate calls when it auto-enables the filter. */
public class CurrentTenant implements Supplier<Long> {
public static volatile long value = 1;
@Override
public Long get() {
return value;
}
}
@@ -0,0 +1,29 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.annotations.Filter;
@Entity
@Table(name = "department")
public class Department {
@Id
Long id;
String name;
@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<>();
public Long getId() { return id; }
public String getName() { return name; }
public List<Task> getTasks() { return tasks; }
public List<Task> getFilteredTasks() { return filteredTasks; }
}
@@ -0,0 +1,27 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
/** autoEnabled = true plus a resolver: every session gets the filter without anyone calling enableFilter(). */
@Entity
@Table(name = "document")
@FilterDef(name = "tenant", defaultCondition = "tenant_id = :tenantId", autoEnabled = true,
parameters = @ParamDef(name = "tenantId", type = Long.class, resolver = CurrentTenant.class))
@Filter(name = "tenant")
public class Document {
@Id
Long id;
String title;
@Column(name = "tenant_id")
long tenantId;
public Long getId() { return id; }
public String getTitle() { return title; }
public long getTenantId() { return tenantId; }
}
@@ -0,0 +1,33 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.annotations.Formula;
/** A @Formula holding a correlated sub-select: an aggregate over child rows, read together with the parent. */
@Entity
@Table(name = "invoice")
public class Invoice {
@Id
Long id;
String customer;
@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;
@OneToMany(mappedBy = "invoice")
List<InvoiceLine> lines = new ArrayList<>();
public Long getId() { return id; }
public String getCustomer() { return customer; }
public BigDecimal getTotal() { return total; }
public int getLineCount() { return lineCount; }
public List<InvoiceLine> getLines() { return lines; }
}
@@ -0,0 +1,30 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "invoice_line")
public class InvoiceLine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "invoice_id")
Invoice invoice;
int qty;
@Column(name = "unit_price")
BigDecimal unitPrice;
public InvoiceLine() { }
public InvoiceLine(Invoice invoice, int qty, BigDecimal unitPrice) {
this.invoice = invoice;
this.qty = qty;
this.unitPrice = unitPrice;
}
}
@@ -0,0 +1,27 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
/** Document's tenant filter with the one missing flag: applyToLoadByKey = true, so find-by-id is scoped too. */
@Entity
@Table(name = "memo")
@FilterDef(name = "memoTenant", defaultCondition = "tenant_id = :tenantId", autoEnabled = true, applyToLoadByKey = true,
parameters = @ParamDef(name = "tenantId", type = Long.class, resolver = CurrentTenant.class))
@Filter(name = "memoTenant")
public class Memo {
@Id
Long id;
String title;
@Column(name = "tenant_id")
long tenantId;
public Long getId() { return id; }
public String getTitle() { return title; }
public long getTenantId() { return tenantId; }
}
@@ -0,0 +1,22 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
/** Points at a Task. If that Task is hidden by @SQLRestriction, this reference dangles. */
@Entity
@Table(name = "note")
public class Note {
@Id
Long id;
String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "task_id")
Task task;
public Long getId() { return id; }
public String getText() { return text; }
public Task getTask() { return task; }
}
@@ -0,0 +1,31 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import org.hibernate.annotations.Formula;
/** 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;
public Long getId() { return id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
}
@@ -0,0 +1,42 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.SQLRestriction;
/**
* Two different mechanisms on one entity:
* <ul>
* <li>{@code @SQLRestriction}: always on, no parameters, cannot be switched off for this entity.</li>
* <li>{@code @Filter}: defined once with {@code @FilterDef}, off until a session enables it, takes parameters.</li>
* </ul>
*/
@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 {
@Id
Long id;
String title;
int priority;
boolean archived;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
Department department;
public Long getId() { return id; }
public String getTitle() { return title; }
public int getPriority() { return priority; }
public boolean isArchived() { return archived; }
public Department getDepartment() { return department; }
}
@@ -0,0 +1,26 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
/** Same idea as Task's filter, but the FilterDef says applyToLoadByKey = true, so session.get() honours it too. */
@Entity
@Table(name = "ticket")
@FilterDef(name = "ticketPriority", defaultCondition = "priority >= :level", applyToLoadByKey = true,
parameters = @ParamDef(name = "level", type = Integer.class))
@Filter(name = "ticketPriority")
public class Ticket {
@Id
Long id;
String title;
int priority;
public Long getId() { return id; }
public String getTitle() { return title; }
public int getPriority() { return priority; }
}
@@ -0,0 +1,19 @@
package com.ankurm.formulafilter;
import jakarta.persistence.*;
import java.math.BigDecimal;
import org.hibernate.annotations.Formula;
/** Invoice again, but the sub-select names qty and unit_price without the "l." alias. */
@Entity
@Table(name = "invoice")
class BrokenFormula {
@Id
Long id;
String customer;
@Formula("(select coalesce(sum(qty * unit_price), 0) from invoice_line l where l.invoice_id = id)")
BigDecimal total;
}
@@ -0,0 +1,106 @@
package com.ankurm.formulafilter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.resource.jdbc.spi.StatementInspector;
/** In-memory H2, one SessionFactory, every prepared SQL statement captured so tests can show and assert it. */
final class Db implements AutoCloseable {
final List<String> sql = new CopyOnWriteArrayList<>();
final SessionFactory sf;
Db(Class<?>... entities) {
StatementInspector inspector = s -> {
sql.add(s);
return s;
};
StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder()
.applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1")
.applySetting("hibernate.connection.username", "sa")
.applySetting("hibernate.connection.password", "")
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
.applySetting("hibernate.session_factory.statement_inspector", inspector);
StandardServiceRegistry reg = b.build();
MetadataSources src = new MetadataSources(reg);
for (Class<?> c : entities) {
src.addAnnotatedClass(c);
}
Metadata md = src.buildMetadata();
this.sf = md.buildSessionFactory();
}
/** Runs native SQL (seed data) in its own transaction; the captured SQL list is cleared afterwards. */
void exec(String... statements) {
try (Session s = sf.openSession()) {
s.doWork(c -> {
for (String st : statements) {
try (var ps = c.createStatement()) {
ps.execute(st);
}
catch (java.sql.SQLException e) {
throw new IllegalStateException(st, e);
}
}
});
}
sql.clear();
}
/** Runs the work inside a transaction on a fresh session and returns the SQL Hibernate prepared. */
List<String> sqlOf(Consumer<Session> work) {
sql.clear();
try (Session s = sf.openSession()) {
var tx = s.beginTransaction();
work.accept(s);
tx.commit();
}
return List.copyOf(sql);
}
/** One transcript step: label, the SQL Hibernate prepared, and what the code returned (or the exception it threw). */
String step(Transcript t, String label, Function<Session, Object> work) {
sql.clear();
String result;
try (Session s = sf.openSession()) {
var tx = s.beginTransaction();
try {
result = String.valueOf(work.apply(s));
tx.commit();
}
catch (RuntimeException ex) {
tx.rollback();
result = ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()).lines().findFirst().orElse("");
}
}
last = List.copyOf(sql);
t.step(label, last);
t.line(" => " + result);
return result;
}
List<String> last = List.of();
<R> R inTx(Function<Session, R> work) {
try (Session s = sf.openSession()) {
var tx = s.beginTransaction();
R r = work.apply(s);
tx.commit();
return r;
}
}
@Override
public void close() {
sf.close();
}
}
@@ -0,0 +1,25 @@
package com.ankurm.formulafilter;
/** The same small data set for every test, inserted with native SQL so Hibernate's own SQL log stays clean. */
final class Seed {
static final Class<?>[] ENTITIES = { Person.class, Invoice.class, InvoiceLine.class, Department.class, Task.class,
Ticket.class, Document.class, Note.class, Memo.class };
static Db open() {
Db db = new Db(ENTITIES);
db.exec(
"insert into person (id, first_name, last_name) values (1, 'Asha', 'Kulkarni'), (2, 'Ravi', 'Patil')",
"insert into invoice (id, customer) values (1, 'Acme'), (2, 'Globex'), (3, 'Initech')",
"insert into invoice_line (invoice_id, qty, unit_price) values (1, 2, 50.00), (1, 1, 30.00), (2, 10, 5.00)",
"insert into department (id, name) values (1, 'Platform'), (2, 'Data')",
"insert into task (id, title, priority, archived, department_id) values "
+ "(1, 'Upgrade JDK', 5, false, 1), (2, 'Rotate logs', 1, false, 1), "
+ "(3, 'Old migration', 4, true, 1), (4, 'Fix flaky test', 3, false, 1), (5, 'Backfill', 2, false, 2)",
"insert into note (id, text, task_id) values (1, 'see the old migration', 3), (2, 'see the JDK upgrade', 1)",
"insert into memo (id, title, tenant_id) values (1, 'Memo A', 1), (2, 'Memo B', 2)",
"insert into ticket (id, title, priority) values (1, 'Typo on login page', 1), (2, 'Payment fails', 5)",
"insert into document (id, title, tenant_id) values (1, 'Q1 plan', 1), (2, 'Q2 plan', 1), (3, 'Other company plan', 2)");
return db;
}
}
@@ -0,0 +1,90 @@
package com.ankurm.formulafilter;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
/** What @Formula does to the SQL, when its value goes stale, and where it can and cannot be used. */
class T01_FormulaTest {
@Test
void formula() {
Transcript t = new Transcript("01-formula", "@Formula: a computed, read-only property (tables person, invoice, invoice_line)");
try (Db db = Seed.open()) {
t.heading("1. A column-less property: no DDL, just a SQL fragment in the SELECT");
String cols = db.step(t, "columns of table person (information_schema)", s -> s.createNativeQuery(
"select column_name from information_schema.columns where table_name = 'PERSON' order by column_name", String.class)
.getResultList());
assertThat(cols).contains("FIRST_NAME", "LAST_NAME").doesNotContain("FULL_NAME", "FULLNAME");
String full = db.step(t, "find(Person, 1).getFullName()", s -> s.find(Person.class, 1L).getFullName());
assertThat(full).isEqualTo("Asha Kulkarni");
assertThat(db.last.getFirst()).contains("p1_0.first_name || ' ' || p1_0.last_name");
t.heading("2. A correlated sub-select: computed on every load of the entity");
String inv = db.step(t, "find(Invoice, 1): total and lineCount", s -> {
Invoice i = s.find(Invoice.class, 1L);
return "total=" + i.getTotal() + " lineCount=" + i.getLineCount();
});
assertThat(inv).isEqualTo("=> total=130.00 lineCount=2".substring(3));
assertThat(db.last).hasSize(1);
assertThat(db.last.getFirst()).contains("l.invoice_id = i1_0.id");
String noLines = db.step(t, "find(Invoice, 3): an invoice with no lines", s -> s.find(Invoice.class, 3L).getTotal());
assertThat(noLines).isEqualTo("0");
t.heading("3. Use it in HQL: the fragment is pasted into WHERE and ORDER BY as well");
String hql = db.step(t, "from Invoice i where i.total > 40 order by i.total desc", s -> s
.createQuery("from Invoice i where i.total > 40 order by i.total desc", Invoice.class).getResultList().stream()
.map(Invoice::getCustomer).toList());
assertThat(hql).isEqualTo("[Acme, Globex]");
long copies = db.last.getFirst().split("select coalesce\\(sum", -1).length - 1;
t.line(" (the total sub-select appears " + copies + " times in that one statement)");
assertThat(copies).isEqualTo(3);
t.heading("4. The price of loading it: a projection that skips the property skips the sub-select");
db.step(t, "select i.id, i.customer from Invoice i", s -> s.createQuery("select i.id, i.customer from Invoice i", Object[].class)
.getResultList().size());
assertThat(db.last.getFirst()).doesNotContain("invoice_line");
db.step(t, "select i.id, i.customer, i.total from Invoice i", s -> s.createQuery(
"select i.id, i.customer, i.total from Invoice i", Object[].class).getResultList().size());
assertThat(db.last.getFirst()).contains("invoice_line");
t.heading("5. Staleness: the value is read once, with the entity");
String stale = db.step(t, "load Globex, add a 100.00 line, flush, read total, refresh, read total", s -> {
Invoice i = s.find(Invoice.class, 2L);
String before = "before=" + i.getTotal();
s.persist(new InvoiceLine(i, 1, new BigDecimal("100.00")));
s.flush();
String afterFlush = "afterFlush=" + i.getTotal();
s.refresh(i);
return before + " " + afterFlush + " afterRefresh=" + i.getTotal();
});
assertThat(stale).isEqualTo("before=50.00 afterFlush=50.00 afterRefresh=150.00");
t.heading("6. Read-only: assigning to the property sends nothing to the database");
db.step(t, "setFullName(\"HACK\"); setLastName(\"Patil-Rao\"); flush", s -> {
Person p = s.find(Person.class, 2L);
p.setFullName("HACK");
p.setLastName("Patil-Rao");
s.flush();
return "full name in memory is now " + p.getFullName();
});
assertThat(db.last).anyMatch(x -> x.startsWith("update person set first_name=?,last_name=?"));
String reread = db.step(t, "fresh session: find(Person, 2).getFullName() (recomputed from the new last_name; HACK is gone)", s -> s.find(Person.class, 2L).getFullName());
assertThat(reread).isEqualTo("Ravi Patil-Rao");
}
t.write();
}
@Test
void unqualifiedColumnInsideSubselect() {
Transcript t = new Transcript("02-formula-unqualified", "@Formula trap: an unqualified column inside a sub-select is aliased to the OUTER table");
try (Db db = new Db(BrokenFormula.class, InvoiceLine.class, Invoice.class)) {
String err = db.step(t, "find(BrokenFormula, 1) with sum(qty * unit_price) and no l. prefix", s -> s.find(BrokenFormula.class, 1L));
assertThat(db.last).hasSize(1);
assertThat(db.last.getFirst()).contains("sum(bf1_0.qty * bf1_0.unit_price)");
assertThat(err).startsWith("SQLGrammarException").contains("BF1_0.QTY\" not found");
}
t.write();
}
}
@@ -0,0 +1,52 @@
package com.ankurm.formulafilter;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/** @SQLRestriction: an always-on WHERE fragment, and every place it reaches (or does not). */
class T03_SqlRestrictionTest {
@Test
void restriction() {
Transcript t = new Transcript("03-sql-restriction", "@SQLRestriction(\"archived = false\") on Task (task 3 'Old migration' is archived)");
try (Db db = Seed.open()) {
t.heading("1. Everywhere Hibernate reads Task rows");
String hql = db.step(t, "from Task", s -> Util.titles(s.createQuery("from Task", Task.class).getResultList()));
assertThat(hql).isEqualTo("[Backfill, Fix flaky test, Rotate logs, Upgrade JDK]");
assertThat(db.last.getFirst()).endsWith("where (t1_0.archived = false)");
String byId = db.step(t, "find(Task, 3): the archived row, by primary key", s -> s.find(Task.class, 3L));
assertThat(byId).isEqualTo("null");
assertThat(db.last.getFirst()).contains("t1_0.id=? and (t1_0.archived = false)");
String coll = db.step(t, "find(Department, 1).getTasks()", s -> Util.titles(s.find(Department.class, 1L).getTasks()));
assertThat(coll).isEqualTo("[Fix flaky test, Rotate logs, Upgrade JDK]");
assertThat(db.last).hasSize(2);
assertThat(db.last.get(1)).contains("t1_0.department_id=? and (t1_0.archived = false)");
String fetch = db.step(t, "select d from Department d join fetch d.tasks where d.id = 1", s -> Util.titles(s.createQuery(
"select d from Department d join fetch d.tasks where d.id = 1", Department.class).getSingleResult().getTasks()));
assertThat(fetch).isEqualTo("[Fix flaky test, Rotate logs, Upgrade JDK]");
assertThat(db.last.getFirst()).contains("on d1_0.id=t1_0.department_id and (t1_0.archived = false)");
t.heading("2. Bulk HQL updates and deletes carry it too");
String upd = db.step(t, "update Task set priority = priority + 10", s -> s.createMutationQuery(
"update Task set priority = priority + 10").executeUpdate());
assertThat(upd).isEqualTo("4");
assertThat(db.last.getFirst()).contains("(t1_0.archived = false)");
t.heading("3. Native SQL is not rewritten");
String nat = db.step(t, "createNativeQuery(\"select count(*) from task\")", s -> s.createNativeQuery("select count(*) from task").getSingleResult());
assertThat(nat).isEqualTo("5");
assertThat(db.last.getFirst()).isEqualTo("select count(*) from task");
t.heading("4. The dangling reference: a Note points at the archived Task");
String dangling = db.step(t, "find(Note, 1).getTask().getTitle()", s -> s.find(Note.class, 1L).getTask().getTitle());
assertThat(dangling).startsWith("ObjectNotFoundException").contains("Task").contains("3");
String live = db.step(t, "find(Note, 2).getTask().getTitle() (points at a live Task)", s -> s.find(Note.class, 2L).getTask().getTitle());
assertThat(live).isEqualTo("Upgrade JDK");
}
t.write();
}
}
@@ -0,0 +1,126 @@
package com.ankurm.formulafilter;
import static org.assertj.core.api.Assertions.assertThat;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
/** @Filter: defined once, off by default, switched on per session with a parameter. */
class T04_FilterTest {
static void on(Session s, int level) {
s.enableFilter("minPriority").setParameter("level", level);
}
@Test
void filter() {
Transcript t = new Transcript("04-filter", "@Filter(\"minPriority\": priority >= :level) on Task, @SQLRestriction(archived = false) also on");
try (Db db = Seed.open()) {
t.heading("1. Defined but not enabled: no effect");
db.step(t, "from Task (filter never enabled)", s -> Util.titles(s.createQuery("from Task", Task.class).getResultList()));
assertThat(db.last.getFirst()).doesNotContain("priority >=");
t.heading("2. Enabled for this session: it is ANDed with the @SQLRestriction");
String hql = db.step(t, "enableFilter(level=3); from Task", s -> {
on(s, 3);
return Util.titles(s.createQuery("from Task", Task.class).getResultList());
});
assertThat(hql).isEqualTo("[Fix flaky test, Upgrade JDK]");
assertThat(db.last.getFirst()).endsWith("where t1_0.priority >= ? and (t1_0.archived = false)");
t.heading("3. The primary-key lookup ignores it (applyToLoadByKey defaults to false)");
String byId = db.step(t, "enableFilter(level=3); find(Task, 2) [Rotate logs has priority 1]", s -> {
on(s, 3);
Task x = s.find(Task.class, 2L);
return x == null ? null : x.getTitle() + " priority=" + x.getPriority();
});
assertThat(byId).isEqualTo("Rotate logs priority=1");
assertThat(db.last.getFirst()).doesNotContain("priority >=").contains("archived = false");
t.heading("4. Collections: an @Filter on the entity does not reach a collection of that entity");
String plain = db.step(t, "enableFilter(level=3); find(Department, 1).getTasks() (collection has no @Filter)", s -> {
Department d = s.find(Department.class, 1L);
on(s, 3);
return Util.titles(d.getTasks());
});
assertThat(plain).isEqualTo("[Fix flaky test, Rotate logs, Upgrade JDK]");
assertThat(db.last.get(1)).doesNotContain("priority >=");
String own = db.step(t, "enableFilter(level=3); find(Department, 1).getFilteredTasks() (collection has its own @Filter)", s -> {
Department d = s.find(Department.class, 1L);
on(s, 3);
return Util.titles(d.getFilteredTasks());
});
assertThat(own).isEqualTo("[Fix flaky test, Upgrade JDK]");
assertThat(db.last.get(1)).contains("t1_0.priority >= ?");
String early = db.step(t, "getFilteredTasks().size() BEFORE enableFilter, then again AFTER", s -> {
Department d = s.find(Department.class, 1L);
int before = d.getFilteredTasks().size();
on(s, 3);
return "before=" + before + " after=" + d.getFilteredTasks().size();
});
assertThat(early).isEqualTo("before=3 after=3");
String fetch = db.step(t, "enableFilter(level=3); join fetch d.filteredTasks", s -> {
on(s, 3);
return Util.titles(s.createQuery("select d from Department d join fetch d.filteredTasks where d.id = 1", Department.class)
.getSingleResult().getFilteredTasks());
});
assertThat(fetch).isEqualTo("[Fix flaky test, Upgrade JDK]");
assertThat(db.last.getFirst()).contains("join task ft1_0 on d1_0.id=ft1_0.department_id and ft1_0.priority >= ?");
t.heading("5. Bulk HQL and native SQL");
String upd = db.step(t, "enableFilter(level=3); update Task set priority = priority + 10", s -> {
on(s, 3);
return s.createMutationQuery("update Task set priority = priority + 10").executeUpdate();
});
assertThat(upd).isEqualTo("2");
assertThat(db.last.getFirst()).contains("t1_0.priority >= ?");
String nat = db.step(t, "enableFilter(level=3); native select count(*) from task", s -> {
on(s, 3);
return s.createNativeQuery("select count(*) from task").getSingleResult();
});
assertThat(nat).isEqualTo("5");
t.heading("6. Scope: one Session, not the SessionFactory");
String sessions = db.step(t, "session A enables level=3; session B (opened by hand) queries", s -> {
on(s, 3);
int a = s.createQuery("from Task", Task.class).getResultList().size();
int b;
try (Session other = db.sf.openSession()) {
b = other.createQuery("from Task", Task.class).getResultList().size();
}
return "sessionA=" + a + " sessionB=" + b;
});
assertThat(sessions).isEqualTo("sessionA=2 sessionB=4");
t.heading("7. Forgetting the parameter");
String noParam = db.step(t, "enableFilter(\"minPriority\") without setParameter; from Task", s -> {
s.enableFilter("minPriority");
return s.createQuery("from Task", Task.class).getResultList().size();
});
assertThat(noParam).isEqualTo("HibernateException: Filter parameter 'minPriority' has neither an argument nor a resolver");
}
t.write();
}
@Test
void applyToLoadByKey() {
Transcript t = new Transcript("05-apply-to-load-by-key", "@FilterDef(applyToLoadByKey = true) on Ticket vs the default on Task");
try (Db db = Seed.open()) {
String get = db.step(t, "enableFilter(ticketPriority, level=3); find(Ticket, 1) [priority 1]", s -> {
s.enableFilter("ticketPriority").setParameter("level", 3);
return s.find(Ticket.class, 1L);
});
assertThat(get).isEqualTo("null");
assertThat(db.last.getFirst()).contains("t1_0.id=? and t1_0.priority >= ?");
String ok = db.step(t, "enableFilter(ticketPriority, level=3); find(Ticket, 2) [priority 5]", s -> {
s.enableFilter("ticketPriority").setParameter("level", 3);
return s.find(Ticket.class, 2L).getTitle();
});
assertThat(ok).isEqualTo("Payment fails");
}
t.write();
}
}
@@ -0,0 +1,49 @@
package com.ankurm.formulafilter;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
/** autoEnabled + a parameter resolver: a tenant filter nobody has to remember to enable, and its one gap. */
class T06_AutoEnabledTest {
@AfterEach
void reset() {
CurrentTenant.value = 1;
}
@Test
void autoEnabled() {
Transcript t = new Transcript("06-auto-enabled", "autoEnabled = true with resolver = CurrentTenant (a Supplier<Long>)");
try (Db db = Seed.open()) {
t.heading("1. No enableFilter() call anywhere");
CurrentTenant.value = 1;
String docs1 = db.step(t, "CurrentTenant=1; from Document", s -> s.createQuery("from Document d order by d.id", Document.class)
.getResultList().stream().map(Document::getTitle).toList());
assertThat(docs1).isEqualTo("[Q1 plan, Q2 plan]");
assertThat(db.last.getFirst()).contains("d1_0.tenant_id = ?");
CurrentTenant.value = 2;
String docs2 = db.step(t, "CurrentTenant=2, new session; from Document", s -> s.createQuery("from Document d order by d.id", Document.class)
.getResultList().stream().map(Document::getTitle).toList());
assertThat(docs2).isEqualTo("[Other company plan]");
t.heading("2. The gap: find-by-id on an entity whose FilterDef lacks applyToLoadByKey");
CurrentTenant.value = 1;
String leak = db.step(t, "CurrentTenant=1; find(Document, 3) [belongs to tenant 2]", s -> {
Document d = s.find(Document.class, 3L);
return d == null ? null : d.getTitle() + " (tenant " + d.getTenantId() + ")";
});
assertThat(leak).isEqualTo("Other company plan (tenant 2)");
assertThat(db.last.getFirst()).endsWith("where d1_0.id=?").doesNotContain("tenant_id = ?");
t.heading("3. The fix: the same definition with applyToLoadByKey = true (entity Memo)");
String blocked = db.step(t, "CurrentTenant=1; find(Memo, 2) [belongs to tenant 2]", s -> s.find(Memo.class, 2L));
assertThat(blocked).isEqualTo("null");
assertThat(db.last.getFirst()).contains("m1_0.id=? and m1_0.tenant_id = ?");
String own = db.step(t, "CurrentTenant=1; find(Memo, 1)", s -> s.find(Memo.class, 1L).getTitle());
assertThat(own).isEqualTo("Memo A");
}
t.write();
}
}
@@ -0,0 +1,61 @@
package com.ankurm.formulafilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects what a test observed and writes output/NN-name.txt; the tests assert the same facts. */
final class Transcript {
static final String VERSION = System.getProperty("h.version", "?");
private final List<String> lines = new ArrayList<>();
private final Path file;
Transcript(String name, String title) {
this.file = Path.of("output", name + ".txt");
line("# " + title);
line("# Hibernate ORM " + VERSION + ", H2 2.4.240, JDK " + Runtime.version().feature());
}
Transcript line(String s) {
lines.add(s);
return this;
}
Transcript heading(String s) {
line("");
return line("== " + s);
}
Transcript lines(List<String> ls, String prefix) {
for (String s : ls) {
line(prefix + s);
}
return this;
}
/** A step: the label, then every SQL statement Hibernate prepared during it. */
Transcript step(String label, List<String> sql) {
line("-- " + label);
if (sql.isEmpty()) {
line(" (no SQL)");
}
for (String s : sql) {
line(" sql> " + s);
}
return this;
}
void write() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
@@ -0,0 +1,15 @@
package com.ankurm.formulafilter;
import java.util.List;
import java.util.stream.Collectors;
final class Util {
static String titles(List<Task> tasks) {
return tasks.stream().map(Task::getTitle).sorted().collect(Collectors.joining(", ", "[", "]"));
}
static boolean anySql(List<String> sql, String fragment) {
return sql.stream().anyMatch(s -> s.contains(fragment));
}
}