Add cascade-types module: JPA cascade types and orphanRemoval on Hibernate 7.4.15.Final and 8.0.0.CR1 (incident reproduced in three schemas, cascade matrix, @OnDelete, delete order)
Plain Hibernate on H2, 14 tests, transcripts in cascade-types/output (h7 and h8). No docs folder. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5sy5qAYYdeYeS1xLW
This commit is contained in:
@@ -350,3 +350,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo
|
|||||||
| [`migration-5-to-7`](migration-5-to-7/) | Hibernate `5.6.15.Final` vs `7.4.14.Final`: jar diff, Hibernate 5 code compiled against both, schema defaults, `hbm2ddl` validation of a Hibernate 5 schema, and cheat-sheet snippets |
|
| [`migration-5-to-7`](migration-5-to-7/) | Hibernate `5.6.15.Final` vs `7.4.14.Final`: jar diff, Hibernate 5 code compiled against both, schema defaults, `hbm2ddl` validation of a Hibernate 5 schema, and cheat-sheet snippets |
|
||||||
| [`multitenancy`](multitenancy/) | Hibernate 7 multi-tenancy on Spring Boot 4.1.2: `@TenantId` discriminator vs schema-per-tenant (shared pool with `search_path`, and pool per tenant), tenant from a JWT claim, the `search_path` leak and the no-tenant failure modes, on PostgreSQL 17 (Hibernate `7.4.14.Final`) |
|
| [`multitenancy`](multitenancy/) | Hibernate 7 multi-tenancy on Spring Boot 4.1.2: `@TenantId` discriminator vs schema-per-tenant (shared pool with `search_path`, and pool per tenant), tenant from a JWT claim, the `search_path` leak and the no-tenant failure modes, on PostgreSQL 17 (Hibernate `7.4.14.Final`) |
|
||||||
| [`json-columns`](json-columns/) | JSON columns in Hibernate 7.4: `@JdbcTypeCode(SqlTypes.JSON)` for Map / List / record / POJO / `@Embeddable`, `json` vs `jsonb` DDL, HQL JSON functions, native JSONB operators, GIN and expression indexes with `EXPLAIN`, dirty checking, Jackson 3 vs Jackson 2 `FormatMapper`, MySQL 8.0, on PostgreSQL 18 (Hibernate `7.4.14.Final`, Spring Boot `4.1.2`) |
|
| [`json-columns`](json-columns/) | JSON columns in Hibernate 7.4: `@JdbcTypeCode(SqlTypes.JSON)` for Map / List / record / POJO / `@Embeddable`, `json` vs `jsonb` DDL, HQL JSON functions, native JSONB operators, GIN and expression indexes with `EXPLAIN`, dirty checking, Jackson 3 vs Jackson 2 `FormatMapper`, MySQL 8.0, on PostgreSQL 18 (Hibernate `7.4.14.Final`, Spring Boot `4.1.2`) |
|
||||||
|
| [`cascade-types`](cascade-types/) | JPA cascade types and `orphanRemoval` in Hibernate 7: composition vs aggregation, `orphanRemoval` vs `CascadeType.REMOVE`, the `cascade = ALL` on `@ManyToOne` incident reproduced in three schemas, `@ManyToMany` / `@OneToOne` / `@ManyToOne` cases, the cost of cascading a 1,000-row delete, `@OnDelete`, and the same tests on Hibernate `8.0.0.CR1`; plain Hibernate on H2 (Hibernate `7.4.15.Final`) |
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# cascade-types
|
||||||
|
|
||||||
|
Companion module for the ankurm.com article **JPA Cascade Types in Hibernate 7: A Decision Tree (Because the Wrong One Will Delete Your Data)**.
|
||||||
|
Every claim in the article comes from a test here; each test writes what it observed to `output/`. Plain Hibernate on an in-memory H2:
|
||||||
|
no Spring, no Docker. The same 14 tests also run on Hibernate 8.0.0.CR1.
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
| Component | Version | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| Hibernate ORM | `7.4.15.Final` | newest 7.x GA listed in `maven-metadata.xml` on 2026-11-15 |
|
||||||
|
| Hibernate ORM (second run) | `8.0.0.CR1` | candidate release, not GA; needs Jakarta Persistence `4.0.0-M8` |
|
||||||
|
| Jakarta Persistence | `3.2.0` | `4.0.0-M8` for the Hibernate 8 run |
|
||||||
|
| H2 | `2.4.240` | in memory |
|
||||||
|
| JUnit / AssertJ | `6.0.3` / `3.27.7` | |
|
||||||
|
| Java | `25` (Temurin 25.0.5+8) | |
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/run-all.sh # both Hibernate versions; regenerates everything in output/
|
||||||
|
mvn clean test # Hibernate 7.4.15.Final only
|
||||||
|
mvn clean test -Dhibernate.version=8.0.0.CR1 -Dpersistence.version=4.0.0-M8 -Dh.label=h8
|
||||||
|
```
|
||||||
|
|
||||||
|
## Entities
|
||||||
|
|
||||||
|
| Entities | Mapping | Used by |
|
||||||
|
|---|---|---|
|
||||||
|
| [`Invoice`](src/main/java/com/ankurm/cascade/Invoice.java) / [`InvoiceLine`](src/main/java/com/ankurm/cascade/InvoiceLine.java) | `@OneToMany(cascade = ALL, orphanRemoval = true)`: composition | T02, T03, T06, T07 |
|
||||||
|
| [`Basket`](src/main/java/com/ankurm/cascade/Basket.java) / [`BasketItem`](src/main/java/com/ankurm/cascade/BasketItem.java) | `cascade = {PERSIST, REMOVE}`, no orphanRemoval | T03 |
|
||||||
|
| [`Folder`](src/main/java/com/ankurm/cascade/Folder.java) / [`Doc`](src/main/java/com/ankurm/cascade/Doc.java) | `cascade = PERSIST` + `orphanRemoval = true`, no REMOVE | T03 |
|
||||||
|
| [`AppUser`](src/main/java/com/ankurm/cascade/AppUser.java), [`ProjectBad`](src/main/java/com/ankurm/cascade/ProjectBad.java), [`ProjectBadDb`](src/main/java/com/ankurm/cascade/ProjectBadDb.java), [`ProjectGood`](src/main/java/com/ankurm/cascade/ProjectGood.java) | the incident: `cascade = ALL` on a shared `@ManyToOne`, with and without `ON DELETE CASCADE`, and the fix | T04, T06, T08 |
|
||||||
|
| [`Writer`](src/main/java/com/ankurm/cascade/Writer.java), [`Comment`](src/main/java/com/ankurm/cascade/Comment.java), [`CommentBad`](src/main/java/com/ankurm/cascade/CommentBad.java) | bad vs improved: cascade flows down, never up | T04 |
|
||||||
|
| [`Student`](src/main/java/com/ankurm/cascade/Student.java), [`CourseBad`](src/main/java/com/ankurm/cascade/CourseBad.java), [`CourseGood`](src/main/java/com/ankurm/cascade/CourseGood.java) | `@ManyToMany`: `ALL` vs `{PERSIST, MERGE}` | T05 |
|
||||||
|
| [`Person`](src/main/java/com/ankurm/cascade/Person.java), [`Profile`](src/main/java/com/ankurm/cascade/Profile.java), [`Address`](src/main/java/com/ankurm/cascade/Address.java) | `@OneToOne`: owned profile cascades, shared address does not | T05 |
|
||||||
|
| [`Ticket`](src/main/java/com/ankurm/cascade/Ticket.java) / [`Agent`](src/main/java/com/ankurm/cascade/Agent.java) | `@ManyToOne(cascade = {PERSIST, MERGE})` | T05 |
|
||||||
|
| [`Ledger`](src/main/java/com/ankurm/cascade/Ledger.java), [`Vault`](src/main/java/com/ankurm/cascade/Vault.java) (+ entries) | `@OnDelete(CASCADE)` alone, and with `cascade = ALL` | T06 |
|
||||||
|
| [`Probe`](src/main/java/com/ankurm/cascade/Probe.java) / [`Leaf`](src/main/java/com/ankurm/cascade/Leaf.java) | one `@OneToOne` per cascade type, to find which operation travels along which | T09 |
|
||||||
|
| [`Board`](src/main/java/com/ankurm/cascade/Board.java) / [`Card`](src/main/java/com/ankurm/cascade/Card.java) | mandatory (`optional = false`) foreign key | T08 |
|
||||||
|
|
||||||
|
## Output
|
||||||
|
|
||||||
|
Each test writes `output/NN-name-h7.txt` (Hibernate 7.4.15.Final) and, on the second run, `output/NN-name-h8.txt` (8.0.0.CR1).
|
||||||
|
Transcript lines starting `sql>` are the SQL strings Hibernate prepared, recorded through a `StatementInspector`; raw JDBC used by the tests to count rows is not recorded.
|
||||||
|
|
||||||
|
| File | What it shows |
|
||||||
|
|---|---|
|
||||||
|
| `01-api-shape` | JPA and Hibernate cascade enums, deprecations, where the cascade engine classes live |
|
||||||
|
| `02-composition` | invoice + lines: persist, unlink one line, remove |
|
||||||
|
| `03-orphan-vs-remove` | the two triggers: unlinking a child, removing the parent |
|
||||||
|
| `04-incident`, `04b-comment-author` | `cascade = ALL` on a shared `@ManyToOne` in three schemas, then the fix |
|
||||||
|
| `05a-many-to-many`, `05b-one-to-one`, `05c-many-to-one` | the decision tree, one relationship type each |
|
||||||
|
| `06a-cascade-remove-cost` | 1,000 lines: cascade REMOVE vs bulk delete first |
|
||||||
|
| `06b-on-delete-cascade` | `@OnDelete`, loaded children, and a cascade that exists only in the schema |
|
||||||
|
| `07a-replace-collection`, `07b-merge-emptied-collection` | orphanRemoval failure modes |
|
||||||
|
| `08-delete-order` | parent removed before child in one flush; Hibernate 8 flush queue |
|
||||||
|
| `09-cascade-matrix` | persist / merge / remove / refresh / detach against each cascade type |
|
||||||
|
|
||||||
|
There is deliberately no `docs/` folder for this module; the explanations are in the article.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Cascade API shape in the shipped jars
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== jakarta.persistence.CascadeType constants
|
||||||
|
ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
|
||||||
|
|
||||||
|
== org.hibernate.annotations.CascadeType (Hibernate's own enum)
|
||||||
|
enum class: present, deprecated(since=7, forRemoval=true)
|
||||||
|
constants: [ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH, LOCK, REPLICATE, DELETE_ORPHAN]
|
||||||
|
has LOCK: true
|
||||||
|
@Cascade annotation: present, deprecated(since=7, forRemoval=true)
|
||||||
|
|
||||||
|
== Internal classes that do the cascading (where each lives in this jar)
|
||||||
|
Cascade org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadingAction org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadingActions org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadeStyle org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadeStyles org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadePoint org.hibernate.engine.internal/spi: present org.hibernate.cascade.internal/spi: absent
|
||||||
|
CascadeEntityPersister (a name the old article used): absent
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Cascade API shape in the shipped jars
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== jakarta.persistence.CascadeType constants
|
||||||
|
ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
|
||||||
|
|
||||||
|
== org.hibernate.annotations.CascadeType (Hibernate's own enum)
|
||||||
|
enum class: absent
|
||||||
|
@Cascade annotation: absent
|
||||||
|
|
||||||
|
== Internal classes that do the cascading (where each lives in this jar)
|
||||||
|
Cascade org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadingAction org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadingActions org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadeStyle org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadeStyles org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadePoint org.hibernate.engine.internal/spi: absent org.hibernate.cascade.internal/spi: present
|
||||||
|
CascadeEntityPersister (a name the old article used): absent
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Composition: Invoice -> InvoiceLine, cascade = ALL + orphanRemoval = true
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== persist(invoice) with two new lines, lines never persisted explicitly
|
||||||
|
-- persist(inv); flush()
|
||||||
|
sql> insert into Invoice (number,id) values (?,default)
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
raw rows: invoice=1 InvoiceLine=2
|
||||||
|
|
||||||
|
== remove one line from the collection (the invoice stays)
|
||||||
|
-- lines.remove(0); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: invoice=1 InvoiceLine=1
|
||||||
|
|
||||||
|
== remove the invoice
|
||||||
|
-- remove(find(Invoice)); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from Invoice where id=?
|
||||||
|
raw rows: invoice=0 InvoiceLine=0
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Composition: Invoice -> InvoiceLine, cascade = ALL + orphanRemoval = true
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== persist(invoice) with two new lines, lines never persisted explicitly
|
||||||
|
-- persist(inv); flush()
|
||||||
|
sql> insert into Invoice (number,id) values (?,default)
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
raw rows: invoice=1 InvoiceLine=2
|
||||||
|
|
||||||
|
== remove one line from the collection (the invoice stays)
|
||||||
|
-- lines.remove(0); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: invoice=1 InvoiceLine=1
|
||||||
|
|
||||||
|
== remove the invoice
|
||||||
|
-- remove(find(Invoice)); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from Invoice where id=?
|
||||||
|
raw rows: invoice=0 InvoiceLine=0
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# orphanRemoval vs cascade = REMOVE
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== Trigger 1: child removed from the parent's collection, parent kept
|
||||||
|
-- Basket (cascade = {PERSIST, REMOVE}, no orphanRemoval): items.remove(0); flush()
|
||||||
|
sql> select b1_0.id from Basket b1_0 where b1_0.id=?
|
||||||
|
sql> select i1_0.basket_id,i1_0.id,i1_0.name from BasketItem i1_0 where i1_0.basket_id=?
|
||||||
|
raw rows: BasketItem=2 (still 2: nothing was deleted)
|
||||||
|
-- Invoice (cascade = ALL, orphanRemoval = true): lines.remove(0); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=1 (now 1: the orphan was deleted)
|
||||||
|
|
||||||
|
== Trigger 2: the parent itself is removed
|
||||||
|
Folder maps cascade = PERSIST and orphanRemoval = true, and has no REMOVE at all
|
||||||
|
-- remove(folder); flush()
|
||||||
|
sql> select f1_0.id from Folder f1_0 where f1_0.id=?
|
||||||
|
sql> select d1_0.folder_id,d1_0.id,d1_0.title from Doc d1_0 where d1_0.folder_id=?
|
||||||
|
sql> delete from Doc where id=?
|
||||||
|
sql> delete from Doc where id=?
|
||||||
|
sql> delete from Folder where id=?
|
||||||
|
raw rows: doc=0 (0: orphanRemoval alone also deletes children when the parent goes)
|
||||||
|
-- Basket (REMOVE, no orphanRemoval): remove(basket); flush()
|
||||||
|
sql> select b1_0.id from Basket b1_0 where b1_0.id=?
|
||||||
|
sql> select i1_0.basket_id,i1_0.id,i1_0.name from BasketItem i1_0 where i1_0.basket_id=?
|
||||||
|
sql> delete from BasketItem where id=?
|
||||||
|
sql> delete from BasketItem where id=?
|
||||||
|
sql> delete from Basket where id=?
|
||||||
|
raw rows: BasketItem=0 basket=0
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# orphanRemoval vs cascade = REMOVE
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== Trigger 1: child removed from the parent's collection, parent kept
|
||||||
|
-- Basket (cascade = {PERSIST, REMOVE}, no orphanRemoval): items.remove(0); flush()
|
||||||
|
sql> select b1_0.id from Basket b1_0 where b1_0.id=?
|
||||||
|
sql> select i1_0.basket_id,i1_0.id,i1_0.name from BasketItem i1_0 where i1_0.basket_id=?
|
||||||
|
raw rows: BasketItem=2 (still 2: nothing was deleted)
|
||||||
|
-- Invoice (cascade = ALL, orphanRemoval = true): lines.remove(0); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=1 (now 1: the orphan was deleted)
|
||||||
|
|
||||||
|
== Trigger 2: the parent itself is removed
|
||||||
|
Folder maps cascade = PERSIST and orphanRemoval = true, and has no REMOVE at all
|
||||||
|
-- remove(folder); flush()
|
||||||
|
sql> select f1_0.id from Folder f1_0 where f1_0.id=?
|
||||||
|
sql> select d1_0.folder_id,d1_0.id,d1_0.title from Doc d1_0 where d1_0.folder_id=?
|
||||||
|
sql> delete from Doc where id=?
|
||||||
|
sql> delete from Folder where id=?
|
||||||
|
raw rows: doc=0 (0: orphanRemoval alone also deletes children when the parent goes)
|
||||||
|
-- Basket (REMOVE, no orphanRemoval): remove(basket); flush()
|
||||||
|
sql> select b1_0.id from Basket b1_0 where b1_0.id=?
|
||||||
|
sql> select i1_0.basket_id,i1_0.id,i1_0.name from BasketItem i1_0 where i1_0.basket_id=?
|
||||||
|
sql> delete from BasketItem where id=?
|
||||||
|
sql> delete from Basket where id=?
|
||||||
|
raw rows: BasketItem=0 basket=0
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# The incident: cascade = ALL on a @ManyToOne to a shared parent
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== Foreign keys on the project tables (ON DELETE rule as H2 reports it)
|
||||||
|
ProjectBad : [FKC2MGHR59KQYACY2C4OQFD1XNP | NO ACTION]
|
||||||
|
ProjectBadDb : [FKDTYHCRAYDD8XEEGIE4S62FQ3P | CASCADE]
|
||||||
|
ProjectGood : [FKNLG47HDNK41TPFKBDSEGG8K9G | NO ACTION]
|
||||||
|
|
||||||
|
== 1. Testing: every project has its own user
|
||||||
|
-- remove(project 1); flush()
|
||||||
|
sql> select pb1_0.id,pb1_0.owner_id,pb1_0.title from ProjectBad pb1_0 where pb1_0.id=?
|
||||||
|
sql> delete from ProjectBad where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
raw rows: AppUser=0 ProjectBad=0 (the user is gone, nothing failed)
|
||||||
|
|
||||||
|
== 2. Production, plain schema: the user has two projects
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pb1_0.id,pb1_0.owner_id,pb1_0.title from ProjectBad pb1_0 where pb1_0.id=?
|
||||||
|
sql> delete from ProjectBad where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
|
||||||
|
cause: Referential integrity constraint violation: "FKC2MGHR59KQYACY2C4OQFD1XNP: PUBLIC.PROJECTBAD FOREIGN KEY(OWNER_ID) REFERENCES PUBLIC.APPUSER(ID) (CAST(2 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: AppUser=1 ProjectBad=2
|
||||||
|
|
||||||
|
== 3. Production, schema with ON DELETE CASCADE on the foreign key
|
||||||
|
before: ProjectBadDb=2
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pbd1_0.id,pbd1_0.owner_id,pbd1_0.title from ProjectBadDb pbd1_0 where pbd1_0.id=?
|
||||||
|
sql> delete from ProjectBadDb where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
raw rows: ProjectBadDb=0 (both projects gone, no error)
|
||||||
|
|
||||||
|
== 4. The fix: ProjectGood, no cascade
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
raw rows: ProjectGood=1 AppUser=1 new user(s) kept
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# The incident: cascade = ALL on a @ManyToOne to a shared parent
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== Foreign keys on the project tables (ON DELETE rule as H2 reports it)
|
||||||
|
ProjectBad : [FKC2MGHR59KQYACY2C4OQFD1XNP | NO ACTION]
|
||||||
|
ProjectBadDb : [FKDTYHCRAYDD8XEEGIE4S62FQ3P | CASCADE]
|
||||||
|
ProjectGood : [FKNLG47HDNK41TPFKBDSEGG8K9G | NO ACTION]
|
||||||
|
|
||||||
|
== 1. Testing: every project has its own user
|
||||||
|
-- remove(project 1); flush()
|
||||||
|
sql> select pb1_0.id,pb1_0.owner_id,pb1_0.title from ProjectBad pb1_0 where pb1_0.id=?
|
||||||
|
sql> delete from ProjectBad where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
raw rows: AppUser=0 ProjectBad=0 (the user is gone, nothing failed)
|
||||||
|
|
||||||
|
== 2. Production, plain schema: the user has two projects
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pb1_0.id,pb1_0.owner_id,pb1_0.title from ProjectBad pb1_0 where pb1_0.id=?
|
||||||
|
sql> delete from ProjectBad where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcBatchUpdateException
|
||||||
|
cause: Referential integrity constraint violation: "FKC2MGHR59KQYACY2C4OQFD1XNP: PUBLIC.PROJECTBAD FOREIGN KEY(OWNER_ID) REFERENCES PUBLIC.APPUSER(ID) (CAST(2 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: AppUser=1 ProjectBad=2
|
||||||
|
|
||||||
|
== 3. Production, schema with ON DELETE CASCADE on the foreign key
|
||||||
|
before: ProjectBadDb=2
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pbd1_0.id,pbd1_0.owner_id,pbd1_0.title from ProjectBadDb pbd1_0 where pbd1_0.id=?
|
||||||
|
sql> delete from ProjectBadDb where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
raw rows: ProjectBadDb=0 (both projects gone, no error)
|
||||||
|
|
||||||
|
== 4. The fix: ProjectGood, no cascade
|
||||||
|
-- remove(first project); flush()
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
raw rows: ProjectGood=1 AppUser=1 new user(s) kept
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Bad -> improved: CommentBad (cascade ALL to the author) vs Comment + Writer.comments
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== Bad: a writer with two comments, delete one
|
||||||
|
-- remove(CommentBad first); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.author_id,cb1_0.text from CommentBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select w1_0.id,w1_0.name from Writer w1_0 where w1_0.id=?
|
||||||
|
sql> select c1_0.author_id,c1_0.id,c1_0.text from Comment c1_0 where c1_0.author_id=?
|
||||||
|
sql> delete from CommentBad where id=?
|
||||||
|
sql> delete from Writer where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
|
||||||
|
cause: Referential integrity constraint violation: "FKI5Y1RDJMEQ4UP89E3R112XDIT: PUBLIC.COMMENTBAD FOREIGN KEY(AUTHOR_ID) REFERENCES PUBLIC.WRITER(ID) (CAST(1 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: Writer=1 CommentBad=2
|
||||||
|
|
||||||
|
== Improved: cascade flows down from Writer to Comment, never up
|
||||||
|
-- remove(Comment one); flush()
|
||||||
|
sql> select c1_0.id,c1_0.author_id,c1_0.text from Comment c1_0 where c1_0.id=?
|
||||||
|
sql> delete from Comment where id=?
|
||||||
|
raw rows: Writer(bob)=1 Comment=1
|
||||||
|
-- remove(Writer bob); flush() (cascade ALL downward)
|
||||||
|
sql> select w1_0.id,w1_0.name from Writer w1_0 where w1_0.id=?
|
||||||
|
sql> select c1_0.author_id,c1_0.id,c1_0.text from Comment c1_0 where c1_0.author_id=?
|
||||||
|
sql> delete from Comment where id=?
|
||||||
|
sql> delete from Writer where id=?
|
||||||
|
raw rows: Comment=0
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Bad -> improved: CommentBad (cascade ALL to the author) vs Comment + Writer.comments
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== Bad: a writer with two comments, delete one
|
||||||
|
-- remove(CommentBad first); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.author_id,cb1_0.text from CommentBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select w1_0.id,w1_0.name from Writer w1_0 where w1_0.id=?
|
||||||
|
sql> select c1_0.author_id,c1_0.id,c1_0.text from Comment c1_0 where c1_0.author_id=?
|
||||||
|
sql> delete from CommentBad where id=?
|
||||||
|
sql> delete from Writer where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcBatchUpdateException
|
||||||
|
cause: Referential integrity constraint violation: "FKI5Y1RDJMEQ4UP89E3R112XDIT: PUBLIC.COMMENTBAD FOREIGN KEY(AUTHOR_ID) REFERENCES PUBLIC.WRITER(ID) (CAST(1 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: Writer=1 CommentBad=2
|
||||||
|
|
||||||
|
== Improved: cascade flows down from Writer to Comment, never up
|
||||||
|
-- remove(Comment one); flush()
|
||||||
|
sql> select c1_0.id,c1_0.author_id,c1_0.text from Comment c1_0 where c1_0.id=?
|
||||||
|
sql> delete from Comment where id=?
|
||||||
|
raw rows: Writer(bob)=1 Comment=1
|
||||||
|
-- remove(Writer bob); flush() (cascade ALL downward)
|
||||||
|
sql> select w1_0.id,w1_0.name from Writer w1_0 where w1_0.id=?
|
||||||
|
sql> select c1_0.author_id,c1_0.id,c1_0.text from Comment c1_0 where c1_0.author_id=?
|
||||||
|
sql> delete from Comment where id=?
|
||||||
|
sql> delete from Writer where id=?
|
||||||
|
raw rows: Comment=0
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# @ManyToMany: cascade ALL vs {PERSIST, MERGE}
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== CourseBad (cascade = ALL): one student enrolled in two courses
|
||||||
|
-- remove(algebra); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.title from CourseBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select s1_0.course_id,s1_1.id,s1_1.name from course_bad_students s1_0 join Student s1_1 on s1_1.id=s1_0.student_id where s1_0.course_id=?
|
||||||
|
sql> delete from course_bad_students where course_id=?
|
||||||
|
sql> delete from Student where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
|
||||||
|
cause: Referential integrity constraint violation: "FKHFU87UUUVAK0UGR0D4KGGPNTC: PUBLIC.COURSE_BAD_STUDENTS FOREIGN KEY(STUDENT_ID) REFERENCES PUBLIC.STUDENT(ID) (CAST(1 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: CourseBad=2 Student=1
|
||||||
|
|
||||||
|
== CourseBad: the same, but the student is only in that one course
|
||||||
|
-- remove(chemistry); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.title from CourseBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select s1_0.course_id,s1_1.id,s1_1.name from course_bad_students s1_0 join Student s1_1 on s1_1.id=s1_0.student_id where s1_0.course_id=?
|
||||||
|
sql> delete from course_bad_students where course_id=?
|
||||||
|
sql> delete from Student where id=?
|
||||||
|
sql> delete from CourseBad where id=?
|
||||||
|
raw rows: Student 2 -> 1 (the student was deleted with the course)
|
||||||
|
|
||||||
|
== CourseGood (cascade = {PERSIST, MERGE})
|
||||||
|
-- remove(dance); flush()
|
||||||
|
sql> select cg1_0.id,cg1_0.title from CourseGood cg1_0 where cg1_0.id=?
|
||||||
|
sql> delete from course_good_students where course_id=?
|
||||||
|
sql> delete from CourseGood where id=?
|
||||||
|
raw rows: Student 3 -> 3 course_good_students=0
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# @ManyToMany: cascade ALL vs {PERSIST, MERGE}
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== CourseBad (cascade = ALL): one student enrolled in two courses
|
||||||
|
-- remove(algebra); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.title from CourseBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select s1_0.course_id,s1_1.id,s1_1.name from course_bad_students s1_0 join Student s1_1 on s1_1.id=s1_0.student_id where s1_0.course_id=?
|
||||||
|
sql> delete from course_bad_students where course_id=?
|
||||||
|
sql> delete from Student where id=?
|
||||||
|
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcBatchUpdateException
|
||||||
|
cause: Referential integrity constraint violation: "FKHFU87UUUVAK0UGR0D4KGGPNTC: PUBLIC.COURSE_BAD_STUDENTS FOREIGN KEY(STUDENT_ID) REFERENCES PUBLIC.STUDENT(ID) (CAST(1 AS BIGINT))"; SQL statement:
|
||||||
|
raw rows after rollback: CourseBad=2 Student=1
|
||||||
|
|
||||||
|
== CourseBad: the same, but the student is only in that one course
|
||||||
|
-- remove(chemistry); flush()
|
||||||
|
sql> select cb1_0.id,cb1_0.title from CourseBad cb1_0 where cb1_0.id=?
|
||||||
|
sql> select s1_0.course_id,s1_1.id,s1_1.name from course_bad_students s1_0 join Student s1_1 on s1_1.id=s1_0.student_id where s1_0.course_id=?
|
||||||
|
sql> delete from course_bad_students where course_id=?
|
||||||
|
sql> delete from Student where id=?
|
||||||
|
sql> delete from CourseBad where id=?
|
||||||
|
raw rows: Student 2 -> 1 (the student was deleted with the course)
|
||||||
|
|
||||||
|
== CourseGood (cascade = {PERSIST, MERGE})
|
||||||
|
-- remove(dance); flush()
|
||||||
|
sql> select cg1_0.id,cg1_0.title from CourseGood cg1_0 where cg1_0.id=?
|
||||||
|
sql> delete from course_good_students where course_id=?
|
||||||
|
sql> delete from CourseGood where id=?
|
||||||
|
raw rows: Student 3 -> 3 course_good_students=0
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# @OneToOne: an owned profile cascades, a shared address does not
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== Persisting a person with a new profile and a new, unsaved address
|
||||||
|
-- persist(person); flush()
|
||||||
|
sql> insert into Profile (bio,id) values (?,default)
|
||||||
|
sql> insert into Person (billingAddress_id,name,profile_id,id) values (?,?,?,default)
|
||||||
|
threw: java.lang.IllegalStateException <- org.hibernate.TransientPropertyValueException
|
||||||
|
cause: Persistent instance of 'com.ankurm.cascade.Person' references an unsaved transient instance of 'com.ankurm.cascade.Address' (persist the transient instance before flushing) [com.ankurm.cascade.Person.billingAddress -> com.ankurm.cascade.Address]
|
||||||
|
raw rows after rollback: Person=0 Profile=0
|
||||||
|
|
||||||
|
== Same, with the shared address persisted first
|
||||||
|
raw rows: Person=1 Profile=1 Address=1
|
||||||
|
-- setProfile(null); flush() (orphanRemoval)
|
||||||
|
sql> select p1_0.id,ba1_0.id,ba1_0.line1,p1_0.name,p2_0.id,p2_0.bio from Person p1_0 left join Address ba1_0 on ba1_0.id=p1_0.billingAddress_id left join Profile p2_0 on p2_0.id=p1_0.profile_id where p1_0.id=?
|
||||||
|
sql> update Person set billingAddress_id=?,name=?,profile_id=? where id=?
|
||||||
|
sql> delete from Profile where id=?
|
||||||
|
raw rows: Profile=0
|
||||||
|
-- remove(person); flush()
|
||||||
|
sql> select p1_0.id,ba1_0.id,ba1_0.line1,p1_0.name,p2_0.id,p2_0.bio from Person p1_0 left join Address ba1_0 on ba1_0.id=p1_0.billingAddress_id left join Profile p2_0 on p2_0.id=p1_0.profile_id where p1_0.id=?
|
||||||
|
sql> delete from Person where id=?
|
||||||
|
sql> delete from Profile where id=?
|
||||||
|
raw rows: Person=0 Profile=0 Address=1 (the address survives)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# @OneToOne: an owned profile cascades, a shared address does not
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== Persisting a person with a new profile and a new, unsaved address
|
||||||
|
-- persist(person); flush()
|
||||||
|
sql> insert into Profile (bio,id) values (?,default)
|
||||||
|
sql> insert into Person (billingAddress_id,name,profile_id,id) values (?,?,?,default)
|
||||||
|
threw: java.lang.IllegalStateException <- org.hibernate.TransientPropertyValueException
|
||||||
|
cause: Persistent instance of 'com.ankurm.cascade.Person' references an unsaved transient instance of 'com.ankurm.cascade.Address' (persist the transient instance before flushing) [com.ankurm.cascade.Person.billingAddress -> com.ankurm.cascade.Address]
|
||||||
|
raw rows after rollback: Person=0 Profile=0
|
||||||
|
|
||||||
|
== Same, with the shared address persisted first
|
||||||
|
raw rows: Person=1 Profile=1 Address=1
|
||||||
|
-- setProfile(null); flush() (orphanRemoval)
|
||||||
|
sql> select p1_0.id,ba1_0.id,ba1_0.line1,p1_0.name,p2_0.id,p2_0.bio from Person p1_0 left join Address ba1_0 on ba1_0.id=p1_0.billingAddress_id left join Profile p2_0 on p2_0.id=p1_0.profile_id where p1_0.id=?
|
||||||
|
sql> update Person set billingAddress_id=?,name=?,profile_id=? where id=?
|
||||||
|
sql> delete from Profile where id=?
|
||||||
|
raw rows: Profile=0
|
||||||
|
-- remove(person); flush()
|
||||||
|
sql> select p1_0.id,ba1_0.id,ba1_0.line1,p1_0.name,p2_0.id,p2_0.bio from Person p1_0 left join Address ba1_0 on ba1_0.id=p1_0.billingAddress_id left join Profile p2_0 on p2_0.id=p1_0.profile_id where p1_0.id=?
|
||||||
|
sql> delete from Person where id=?
|
||||||
|
sql> delete from Profile where id=?
|
||||||
|
raw rows: Person=0 Profile=0 Address=1 (the address survives)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# @ManyToOne with cascade = {PERSIST, MERGE}: what it is for, and what it cannot do
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== New parent created together with its first child
|
||||||
|
-- persist(new Ticket(.., new Agent())); flush()
|
||||||
|
sql> insert into Agent (name,id) values (?,default)
|
||||||
|
sql> insert into Ticket (agent_id,subject,id) values (?,?,default)
|
||||||
|
raw rows: Ticket=1 Agent=1
|
||||||
|
|
||||||
|
== Parent already exists (a detached Agent): persist vs merge
|
||||||
|
-- persist(new Ticket(.., detachedAgent)); flush()
|
||||||
|
(no SQL)
|
||||||
|
threw: jakarta.persistence.EntityExistsException <- org.hibernate.PersistentObjectException
|
||||||
|
cause: Detached entity passed to persist: com.ankurm.cascade.Agent
|
||||||
|
-- merge(new Ticket(.., detachedAgent)); flush()
|
||||||
|
sql> select a1_0.id,a1_0.name from Agent a1_0 where a1_0.id=?
|
||||||
|
sql> insert into Ticket (agent_id,subject,id) values (?,?,default)
|
||||||
|
raw rows: Ticket=2 Agent=2
|
||||||
|
|
||||||
|
== Removing a ticket never touches its agent
|
||||||
|
-- remove(ticket); flush()
|
||||||
|
sql> select t1_0.id,a1_0.id,a1_0.name,t1_0.subject from Ticket t1_0 left join Agent a1_0 on a1_0.id=t1_0.agent_id where t1_0.id=?
|
||||||
|
sql> delete from Ticket where id=?
|
||||||
|
raw rows: Ticket=1 Agent=2
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# @ManyToOne with cascade = {PERSIST, MERGE}: what it is for, and what it cannot do
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== New parent created together with its first child
|
||||||
|
-- persist(new Ticket(.., new Agent())); flush()
|
||||||
|
sql> insert into Agent (name,id) values (?,default)
|
||||||
|
sql> insert into Ticket (agent_id,subject,id) values (?,?,default)
|
||||||
|
raw rows: Ticket=1 Agent=1
|
||||||
|
|
||||||
|
== Parent already exists (a detached Agent): persist vs merge
|
||||||
|
-- persist(new Ticket(.., detachedAgent)); flush()
|
||||||
|
(no SQL)
|
||||||
|
threw: jakarta.persistence.EntityExistsException <- org.hibernate.PersistentObjectException
|
||||||
|
cause: Detached entity passed to persist: com.ankurm.cascade.Agent
|
||||||
|
-- merge(new Ticket(.., detachedAgent)); flush()
|
||||||
|
sql> select a1_0.id,a1_0.name from Agent a1_0 where a1_0.id=?
|
||||||
|
sql> insert into Ticket (agent_id,subject,id) values (?,?,default)
|
||||||
|
raw rows: Ticket=2 Agent=2
|
||||||
|
|
||||||
|
== Removing a ticket never touches its agent
|
||||||
|
-- remove(ticket); flush()
|
||||||
|
sql> select t1_0.id,a1_0.id,a1_0.name,t1_0.subject from Ticket t1_0 left join Agent a1_0 on a1_0.id=t1_0.agent_id where t1_0.id=?
|
||||||
|
sql> delete from Ticket where id=?
|
||||||
|
raw rows: Ticket=1 Agent=2
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Removing an invoice with 1000 lines: cascade REMOVE vs bulk delete first
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
effective hibernate.jdbc.batch_size: 15
|
||||||
|
|
||||||
|
== A. em.remove(invoice) with cascade = ALL, lines never touched by the code
|
||||||
|
entities in the persistence context after find(): 1
|
||||||
|
entities in the persistence context after remove(): 1001
|
||||||
|
entities deleted (Hibernate statistics): 1001
|
||||||
|
SQL strings prepared: total=1003 select=2 delete=1001
|
||||||
|
first statements:
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
|
||||||
|
== A2. the same removal with hibernate.flush.queue.type=legacy (ignored by 7.x)
|
||||||
|
SQL strings prepared: total=1003 select=2 delete=1001
|
||||||
|
|
||||||
|
== B. bulk delete of the lines first, then remove(getReference(invoice))
|
||||||
|
entities in the persistence context after remove(): 1
|
||||||
|
entities deleted (Hibernate statistics): 1
|
||||||
|
SQL strings prepared: total=4 select=2 delete=2
|
||||||
|
sql> delete from InvoiceLine il1_0 where il1_0.invoice_id=?
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from Invoice where id=?
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Removing an invoice with 1000 lines: cascade REMOVE vs bulk delete first
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
effective hibernate.jdbc.batch_size: 15
|
||||||
|
|
||||||
|
== A. em.remove(invoice) with cascade = ALL, lines never touched by the code
|
||||||
|
entities in the persistence context after find(): 1
|
||||||
|
entities in the persistence context after remove(): 1001
|
||||||
|
entities deleted (Hibernate statistics): 1001
|
||||||
|
SQL strings prepared: total=4 select=2 delete=2
|
||||||
|
first statements:
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from Invoice where id=?
|
||||||
|
|
||||||
|
== A2. the same removal with hibernate.flush.queue.type=legacy (ignored by 7.x)
|
||||||
|
SQL strings prepared: total=1003 select=2 delete=1001
|
||||||
|
|
||||||
|
== B. bulk delete of the lines first, then remove(getReference(invoice))
|
||||||
|
entities in the persistence context after remove(): 1
|
||||||
|
entities deleted (Hibernate statistics): 1
|
||||||
|
SQL strings prepared: total=4 select=2 delete=2
|
||||||
|
sql> delete from InvoiceLine il1_0 where il1_0.invoice_id=?
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from Invoice where id=?
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# @OnDelete(CASCADE): the database deletes the children, Hibernate does not know
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
LedgerEntry foreign key: [FKJW461MHMPCBIN06DVK8AU5D6F | CASCADE]
|
||||||
|
VaultEntry foreign key: [FK84JU8V00N04VVRD9SKS3NCU3I | CASCADE]
|
||||||
|
|
||||||
|
== 1. Ledger: @OnDelete only, children never loaded
|
||||||
|
-- remove(find(Ledger)); flush()
|
||||||
|
sql> select l1_0.id from Ledger l1_0 where l1_0.id=?
|
||||||
|
sql> delete from Ledger where id=?
|
||||||
|
raw rows: Ledger=0 LedgerEntry=0
|
||||||
|
|
||||||
|
== 2. Ledger: @OnDelete only, but the entries are already loaded in the session
|
||||||
|
-- find(Ledger); entries.size(); remove(ledger); flush()
|
||||||
|
sql> select l1_0.id from Ledger l1_0 where l1_0.id=?
|
||||||
|
sql> select e1_0.ledger_id,e1_0.id,e1_0.memo from LedgerEntry e1_0 where e1_0.ledger_id=?
|
||||||
|
threw: java.lang.IllegalStateException <- org.hibernate.TransientPropertyValueException
|
||||||
|
cause: Persistent instance of 'com.ankurm.cascade.LedgerEntry' references an unsaved transient instance of 'com.ankurm.cascade.Ledger' (persist the transient instance before flushing) [com.ankurm.cascade.LedgerEntry.ledger -> com.ankurm.cascade.Ledger]
|
||||||
|
|
||||||
|
== 3. Vault: cascade = ALL plus @OnDelete, entries loaded
|
||||||
|
-- find(Vault); remove(vault); flush()
|
||||||
|
sql> delete from Vault where id=?
|
||||||
|
raw rows after commit: Vault=0 VaultEntry=0
|
||||||
|
same session, contains(firstEntry) after commit: false
|
||||||
|
same session, find(VaultEntry first): null
|
||||||
|
|
||||||
|
== 4. A cascade that only exists in the schema: the mapping (ProjectGood -> AppUser) says nothing about it
|
||||||
|
ProjectGood foreign key now: [FK_PROJECT_OWNER | CASCADE]
|
||||||
|
-- native: delete from AppUser where id = ?
|
||||||
|
sql> delete from AppUser where id = ?
|
||||||
|
raw rows: AppUser(id)=0 ProjectGood(id)=0
|
||||||
|
same session, find(ProjectGood) -> still returns the deleted project
|
||||||
|
SQL issued by that find: 0
|
||||||
|
same session, contains(project): true
|
||||||
|
after session.clear(), find(ProjectGood) -> null
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# @OnDelete(CASCADE): the database deletes the children, Hibernate does not know
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
LedgerEntry foreign key: [FKJW461MHMPCBIN06DVK8AU5D6F | CASCADE]
|
||||||
|
VaultEntry foreign key: [FK84JU8V00N04VVRD9SKS3NCU3I | CASCADE]
|
||||||
|
|
||||||
|
== 1. Ledger: @OnDelete only, children never loaded
|
||||||
|
-- remove(find(Ledger)); flush()
|
||||||
|
sql> select l1_0.id from Ledger l1_0 where l1_0.id=?
|
||||||
|
sql> delete from Ledger where id=?
|
||||||
|
raw rows: Ledger=0 LedgerEntry=0
|
||||||
|
|
||||||
|
== 2. Ledger: @OnDelete only, but the entries are already loaded in the session
|
||||||
|
-- find(Ledger); entries.size(); remove(ledger); flush()
|
||||||
|
sql> select l1_0.id from Ledger l1_0 where l1_0.id=?
|
||||||
|
sql> select e1_0.ledger_id,e1_0.id,e1_0.memo from LedgerEntry e1_0 where e1_0.ledger_id=?
|
||||||
|
threw: java.lang.IllegalStateException <- org.hibernate.TransientPropertyValueException
|
||||||
|
cause: Persistent instance of 'com.ankurm.cascade.LedgerEntry' references an unsaved transient instance of 'com.ankurm.cascade.Ledger' (persist the transient instance before flushing) [com.ankurm.cascade.LedgerEntry.ledger -> com.ankurm.cascade.Ledger]
|
||||||
|
|
||||||
|
== 3. Vault: cascade = ALL plus @OnDelete, entries loaded
|
||||||
|
-- find(Vault); remove(vault); flush()
|
||||||
|
sql> delete from Vault where id=?
|
||||||
|
raw rows after commit: Vault=0 VaultEntry=0
|
||||||
|
same session, contains(firstEntry) after commit: false
|
||||||
|
same session, find(VaultEntry first): null
|
||||||
|
|
||||||
|
== 4. A cascade that only exists in the schema: the mapping (ProjectGood -> AppUser) says nothing about it
|
||||||
|
ProjectGood foreign key now: [FK_PROJECT_OWNER | CASCADE]
|
||||||
|
-- native: delete from AppUser where id = ?
|
||||||
|
sql> delete from AppUser where id = ?
|
||||||
|
raw rows: AppUser(id)=0 ProjectGood(id)=0
|
||||||
|
same session, find(ProjectGood) -> still returns the deleted project
|
||||||
|
SQL issued by that find: 0
|
||||||
|
same session, contains(project): true
|
||||||
|
after session.clear(), find(ProjectGood) -> null
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# orphanRemoval: replacing the collection instead of changing it
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== setLines(new ArrayList<>()) on a managed invoice
|
||||||
|
-- setLines(new ArrayList<>()); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
threw: org.hibernate.HibernateException
|
||||||
|
cause: A collection with orphan deletion was no longer referenced by the owning entity instance: com.ankurm.cascade.Invoice.lines
|
||||||
|
raw rows after rollback: InvoiceLine=2
|
||||||
|
|
||||||
|
== The safe way: clear() the existing collection
|
||||||
|
-- getLines().clear(); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=0
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# orphanRemoval: replacing the collection instead of changing it
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== setLines(new ArrayList<>()) on a managed invoice
|
||||||
|
-- setLines(new ArrayList<>()); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
threw: org.hibernate.HibernateException
|
||||||
|
cause: A collection with orphan deletion was no longer referenced by the owning entity instance: com.ankurm.cascade.Invoice.lines
|
||||||
|
raw rows after rollback: InvoiceLine=2
|
||||||
|
|
||||||
|
== The safe way: clear() the existing collection
|
||||||
|
-- getLines().clear(); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=0
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# orphanRemoval and merge(): managed parent, emptied collection (reported as a 6.6 -> 7.x regression)
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== 1. managed invoice, getLines().clear(), merge(invoice), flush()
|
||||||
|
-- clear(); merge(inv); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=0
|
||||||
|
|
||||||
|
== 2. managed invoice, clear(), add one new line, merge(invoice), flush()
|
||||||
|
-- clear(); addLine(); merge(inv); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows for invoice M-2 lines: [replacement]
|
||||||
|
|
||||||
|
== 3. the normal detached round trip: load, close session, remove a line, merge in a new session
|
||||||
|
-- merge(detachedInvoice); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number,l1_0.invoice_id,l1_0.id,l1_0.description from Invoice i1_0 left join InvoiceLine l1_0 on i1_0.id=l1_0.invoice_id where i1_0.id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows for invoice M-3 lines: [2]
|
||||||
|
outcomes: 1=ok 2=ok 3=ok
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# orphanRemoval and merge(): managed parent, emptied collection (reported as a 6.6 -> 7.x regression)
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== 1. managed invoice, getLines().clear(), merge(invoice), flush()
|
||||||
|
-- clear(); merge(inv); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows: InvoiceLine=0
|
||||||
|
|
||||||
|
== 2. managed invoice, clear(), add one new line, merge(invoice), flush()
|
||||||
|
-- clear(); addLine(); merge(inv); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number from Invoice i1_0 where i1_0.id=?
|
||||||
|
sql> select l1_0.invoice_id,l1_0.id,l1_0.description from InvoiceLine l1_0 where l1_0.invoice_id=?
|
||||||
|
sql> insert into InvoiceLine (description,invoice_id,id) values (?,?,default)
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows for invoice M-2 lines: [replacement]
|
||||||
|
|
||||||
|
== 3. the normal detached round trip: load, close session, remove a line, merge in a new session
|
||||||
|
-- merge(detachedInvoice); flush()
|
||||||
|
sql> select i1_0.id,i1_0.number,l1_0.invoice_id,l1_0.id,l1_0.description from Invoice i1_0 left join InvoiceLine l1_0 on i1_0.id=l1_0.invoice_id where i1_0.id=?
|
||||||
|
sql> delete from InvoiceLine where id=?
|
||||||
|
raw rows for invoice M-3 lines: [2]
|
||||||
|
outcomes: 1=ok 2=ok 3=ok
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Deleting a parent and its (non-cascaded) child in one flush, parent removed first
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
|
||||||
|
== ProjectGood.owner is nullable
|
||||||
|
-- default settings
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select au1_0.id,au1_0.name from AppUser au1_0 where au1_0.id=?
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> update ProjectGood set owner_id=?,title=? where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
raw rows: parent=0 child=0
|
||||||
|
-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select au1_0.id,au1_0.name from AppUser au1_0 where au1_0.id=?
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> update ProjectGood set owner_id=?,title=? where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
raw rows: parent=0 child=0
|
||||||
|
|
||||||
|
== Card.board is optional = false (the foreign key cannot be nulled)
|
||||||
|
-- default settings
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select b1_0.id,b1_0.name from Board b1_0 where b1_0.id=?
|
||||||
|
sql> select c1_0.id,c1_0.board_id,b1_0.id,b1_0.name,c1_0.title from Card c1_0 join Board b1_0 on b1_0.id=c1_0.board_id where c1_0.id=?
|
||||||
|
threw: org.hibernate.PropertyValueException
|
||||||
|
cause: not-null property references a null or transient value for entity com.ankurm.cascade.Card.board
|
||||||
|
raw rows: parent=1 child=1
|
||||||
|
-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select b1_0.id,b1_0.name from Board b1_0 where b1_0.id=?
|
||||||
|
sql> select c1_0.id,c1_0.board_id,b1_0.id,b1_0.name,c1_0.title from Card c1_0 join Board b1_0 on b1_0.id=c1_0.board_id where c1_0.id=?
|
||||||
|
threw: org.hibernate.PropertyValueException
|
||||||
|
cause: not-null property references a null or transient value for entity com.ankurm.cascade.Card.board
|
||||||
|
raw rows: parent=1 child=1
|
||||||
|
|
||||||
|
outcomes: nullable default=ok/first delete: AppUser | nullable legacy=ok/first delete: AppUser | mandatory default=threw/first delete: none | mandatory legacy=threw/first delete: none
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Deleting a parent and its (non-cascaded) child in one flush, parent removed first
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
|
||||||
|
== ProjectGood.owner is nullable
|
||||||
|
-- default settings
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select au1_0.id,au1_0.name from AppUser au1_0 where au1_0.id=?
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> update ProjectGood set owner_id=?,title=? where id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
raw rows: parent=0 child=0
|
||||||
|
-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select au1_0.id,au1_0.name from AppUser au1_0 where au1_0.id=?
|
||||||
|
sql> select pg1_0.id,pg1_0.owner_id,pg1_0.title from ProjectGood pg1_0 where pg1_0.id=?
|
||||||
|
sql> update ProjectGood set owner_id=?,title=? where id=?
|
||||||
|
sql> delete from AppUser where id=?
|
||||||
|
sql> delete from ProjectGood where id=?
|
||||||
|
raw rows: parent=0 child=0
|
||||||
|
|
||||||
|
== Card.board is optional = false (the foreign key cannot be nulled)
|
||||||
|
-- default settings
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select b1_0.id,b1_0.name from Board b1_0 where b1_0.id=?
|
||||||
|
sql> select c1_0.id,c1_0.board_id,b1_0.id,b1_0.name,c1_0.title from Card c1_0 join Board b1_0 on b1_0.id=c1_0.board_id where c1_0.id=?
|
||||||
|
threw: org.hibernate.PropertyValueException
|
||||||
|
cause: not-null property references a null or transient value for entity com.ankurm.cascade.Card.board
|
||||||
|
raw rows: parent=1 child=1
|
||||||
|
-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)
|
||||||
|
-- remove(parent); remove(child); flush()
|
||||||
|
sql> select b1_0.id,b1_0.name from Board b1_0 where b1_0.id=?
|
||||||
|
sql> select c1_0.id,c1_0.board_id,b1_0.id,b1_0.name,c1_0.title from Card c1_0 join Board b1_0 on b1_0.id=c1_0.board_id where c1_0.id=?
|
||||||
|
threw: org.hibernate.PropertyValueException
|
||||||
|
cause: not-null property references a null or transient value for entity com.ankurm.cascade.Card.board
|
||||||
|
raw rows: parent=1 child=1
|
||||||
|
|
||||||
|
outcomes: nullable default=ok/first delete: ProjectGood | nullable legacy=ok/first delete: AppUser | mandatory default=threw/first delete: none | mandatory legacy=threw/first delete: none
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Which operation propagates along which cascade type (one @OneToOne per type, all to Leaf)
|
||||||
|
# Hibernate ORM 7.4.15.Final, H2, JDK 25
|
||||||
|
persist() propagates along: [onPersist, onAll]
|
||||||
|
merge() propagates along: [onMerge, onAll]
|
||||||
|
remove() propagates along: [onRemove, onAll]
|
||||||
|
refresh() propagates along: [onRefresh, onAll]
|
||||||
|
detach() propagates along: [onDetach, onAll]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Which operation propagates along which cascade type (one @OneToOne per type, all to Leaf)
|
||||||
|
# Hibernate ORM 8.0.0.CR1, H2, JDK 25
|
||||||
|
persist() propagates along: [onPersist, onAll]
|
||||||
|
merge() propagates along: [onMerge, onAll]
|
||||||
|
remove() propagates along: [onRemove, onAll]
|
||||||
|
refresh() propagates along: [onRefresh, onAll]
|
||||||
|
detach() propagates along: [onDetach, onAll]
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?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>cascade-types</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>cascade-types</name>
|
||||||
|
<description>JPA cascade types and orphanRemoval in Hibernate 7, run with plain Hibernate (no Spring) on H2; the same tests also run on Hibernate 8.0.0.CR1</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<!-- Newest 7.x GA on Maven Central on 2026-11-15 (maven-metadata.xml lists 8.0.0.CR1 after it; CR1 is not GA).
|
||||||
|
Run the same tests on Hibernate 8 with:
|
||||||
|
mvn clean test -Dhibernate.version=8.0.0.CR1 -Dpersistence.version=4.0.0-M8 -Dh.label=h8 -->
|
||||||
|
<hibernate.version>7.4.15.Final</hibernate.version>
|
||||||
|
<persistence.version>3.2.0</persistence.version>
|
||||||
|
<h.label>h7</h.label>
|
||||||
|
</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.label>${h.label}</h.label>
|
||||||
|
<h.version>${hibernate.version}</h.version>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file under output/. Needs JDK 25, Maven 3.9 and network access to Maven Central (no Docker: H2 only).
|
||||||
|
# ./scripts/run-all.sh
|
||||||
|
# Runs the whole suite twice: Hibernate 7.4.15.Final (writes output/*-h7.txt), then Hibernate 8.0.0.CR1 (writes output/*-h8.txt).
|
||||||
|
# `clean` between the two runs matters: stale classes compiled against the other Jakarta Persistence API link wrongly.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mvn -B clean test
|
||||||
|
mvn -B clean test -Dhibernate.version=8.0.0.CR1 -Dpersistence.version=4.0.0-M8 -Dh.label=h8
|
||||||
|
ls -1 output
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Address {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String line1;
|
||||||
|
|
||||||
|
protected Address() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Address(String line1) {
|
||||||
|
this.line1 = line1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Agent {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
protected Agent() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Agent(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
/** Called AppUser, not User, because USER is a reserved word in H2 and PostgreSQL. A shared parent: many projects point at one user. */
|
||||||
|
@Entity
|
||||||
|
public class AppUser {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
protected AppUser() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public AppUser(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** cascade = REMOVE (plus PERSIST) but no orphanRemoval: deleting the basket deletes items, unlinking an item does not. */
|
||||||
|
@Entity
|
||||||
|
public class Basket {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "basket", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
|
||||||
|
private List<BasketItem> items = new ArrayList<>();
|
||||||
|
|
||||||
|
public BasketItem add(String name) {
|
||||||
|
BasketItem item = new BasketItem(this, name);
|
||||||
|
items.add(item);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BasketItem> getItems() {
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class BasketItem {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "basket_id")
|
||||||
|
private Basket basket;
|
||||||
|
|
||||||
|
protected BasketItem() {
|
||||||
|
}
|
||||||
|
|
||||||
|
BasketItem(Basket basket, String name) {
|
||||||
|
this.basket = basket;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
/** Parent in a mandatory relationship: every Card must belong to a board, so a card's foreign key can never be nulled. */
|
||||||
|
@Entity
|
||||||
|
public class Board {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
protected Board() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Card {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToOne(optional = false)
|
||||||
|
@JoinColumn(name = "board_id", nullable = false)
|
||||||
|
private Board board;
|
||||||
|
|
||||||
|
protected Card() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Card(String title, Board board) {
|
||||||
|
this.title = title;
|
||||||
|
this.board = board;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Comment {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String text;
|
||||||
|
|
||||||
|
// No cascade: the writer outlives any individual comment
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "author_id")
|
||||||
|
private Writer author;
|
||||||
|
|
||||||
|
protected Comment() {
|
||||||
|
}
|
||||||
|
|
||||||
|
Comment(Writer author, String text) {
|
||||||
|
this.author = author;
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
/** Bad: deleting any comment tries to delete its author. */
|
||||||
|
@Entity
|
||||||
|
public class CommentBad {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String text;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||||
|
@JoinColumn(name = "author_id")
|
||||||
|
private Writer author;
|
||||||
|
|
||||||
|
protected CommentBad() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public CommentBad(Writer author, String text) {
|
||||||
|
this.author = author;
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinTable;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToMany;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** Bad: cascade ALL on a @ManyToMany includes REMOVE, so deleting the course deletes its students. */
|
||||||
|
@Entity
|
||||||
|
public class CourseBad {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToMany(cascade = CascadeType.ALL)
|
||||||
|
@JoinTable(name = "course_bad_students",
|
||||||
|
joinColumns = @JoinColumn(name = "course_id"),
|
||||||
|
inverseJoinColumns = @JoinColumn(name = "student_id"))
|
||||||
|
private Set<Student> students = new HashSet<>();
|
||||||
|
|
||||||
|
protected CourseBad() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public CourseBad(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Student> getStudents() {
|
||||||
|
return students;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.JoinTable;
|
||||||
|
import jakarta.persistence.ManyToMany;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** Aggregation: PERSIST and MERGE so saving a course saves new students; deleting a course removes only the join rows. */
|
||||||
|
@Entity
|
||||||
|
public class CourseGood {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||||
|
@JoinTable(name = "course_good_students",
|
||||||
|
joinColumns = @JoinColumn(name = "course_id"),
|
||||||
|
inverseJoinColumns = @JoinColumn(name = "student_id"))
|
||||||
|
private Set<Student> students = new HashSet<>();
|
||||||
|
|
||||||
|
protected CourseGood() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public CourseGood(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Student> getStudents() {
|
||||||
|
return students;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Doc {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "folder_id")
|
||||||
|
private Folder folder;
|
||||||
|
|
||||||
|
protected Doc() {
|
||||||
|
}
|
||||||
|
|
||||||
|
Doc(Folder folder, String title) {
|
||||||
|
this.folder = folder;
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTitle() {
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** orphanRemoval = true and cascade = PERSIST only. There is deliberately no REMOVE here; see T03_OrphanVsRemoveTest. */
|
||||||
|
@Entity
|
||||||
|
public class Folder {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "folder", cascade = CascadeType.PERSIST, orphanRemoval = true)
|
||||||
|
private List<Doc> docs = new ArrayList<>();
|
||||||
|
|
||||||
|
public Doc add(String title) {
|
||||||
|
Doc d = new Doc(this, title);
|
||||||
|
docs.add(d);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Doc> getDocs() {
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Composition: a line is meaningless without its invoice, so the invoice owns the line's whole lifecycle. */
|
||||||
|
@Entity
|
||||||
|
public class Invoice {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String number;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "invoice",
|
||||||
|
cascade = CascadeType.ALL,
|
||||||
|
orphanRemoval = true)
|
||||||
|
private List<InvoiceLine> lines = new ArrayList<>();
|
||||||
|
|
||||||
|
protected Invoice() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Invoice(String number) {
|
||||||
|
this.number = number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public InvoiceLine addLine(String description) {
|
||||||
|
InvoiceLine line = new InvoiceLine(this, description);
|
||||||
|
lines.add(line);
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getNumber() {
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<InvoiceLine> getLines() {
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the collection object itself: the classic way to break orphanRemoval. */
|
||||||
|
public void setLines(List<InvoiceLine> lines) {
|
||||||
|
this.lines = lines;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
/** The child side: no cascade back to the invoice, because a line must never decide the invoice's fate. */
|
||||||
|
@Entity
|
||||||
|
public class InvoiceLine {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "invoice_id")
|
||||||
|
private Invoice invoice;
|
||||||
|
|
||||||
|
protected InvoiceLine() {
|
||||||
|
}
|
||||||
|
|
||||||
|
InvoiceLine(Invoice invoice, String description) {
|
||||||
|
this.invoice = invoice;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Leaf {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String label;
|
||||||
|
|
||||||
|
protected Leaf() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Leaf(String label) {
|
||||||
|
this.label = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLabel() {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabel(String label) {
|
||||||
|
this.label = label;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.hibernate.annotations.OnDelete;
|
||||||
|
import org.hibernate.annotations.OnDeleteAction;
|
||||||
|
|
||||||
|
/** Database-level cascade: no JPA cascade at all; the foreign key says ON DELETE CASCADE and Hibernate trusts it. */
|
||||||
|
@Entity
|
||||||
|
public class Ledger {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "ledger")
|
||||||
|
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||||
|
private List<LedgerEntry> entries = new ArrayList<>();
|
||||||
|
|
||||||
|
public LedgerEntry add(String memo) {
|
||||||
|
LedgerEntry e = new LedgerEntry(this, memo);
|
||||||
|
entries.add(e);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<LedgerEntry> getEntries() {
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class LedgerEntry {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String memo;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "ledger_id")
|
||||||
|
private Ledger ledger;
|
||||||
|
|
||||||
|
protected LedgerEntry() {
|
||||||
|
}
|
||||||
|
|
||||||
|
LedgerEntry(Ledger ledger, String memo) {
|
||||||
|
this.ledger = ledger;
|
||||||
|
this.memo = memo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToOne;
|
||||||
|
|
||||||
|
/** Two @OneToOne associations, two different answers: an owned profile cascades, a shared billing address does not. */
|
||||||
|
@Entity
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Owned: the profile only makes sense attached to this person. */
|
||||||
|
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
|
private Profile profile;
|
||||||
|
|
||||||
|
/** Shared: several people may live at, and be billed to, the same address. */
|
||||||
|
@OneToOne
|
||||||
|
private Address billingAddress;
|
||||||
|
|
||||||
|
protected Person() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Person(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Profile getProfile() {
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setProfile(Profile profile) {
|
||||||
|
this.profile = profile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Address getBillingAddress() {
|
||||||
|
return billingAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBillingAddress(Address billingAddress) {
|
||||||
|
this.billingAddress = billingAddress;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToOne;
|
||||||
|
|
||||||
|
/** One association per cascade type, all pointing at {@link Leaf}, so a test can see which operation travels along which one. */
|
||||||
|
@Entity
|
||||||
|
public class Probe {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.PERSIST)
|
||||||
|
private Leaf onPersist;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.MERGE)
|
||||||
|
private Leaf onMerge;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.REMOVE)
|
||||||
|
private Leaf onRemove;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.REFRESH)
|
||||||
|
private Leaf onRefresh;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.DETACH)
|
||||||
|
private Leaf onDetach;
|
||||||
|
|
||||||
|
@OneToOne(cascade = CascadeType.ALL)
|
||||||
|
private Leaf onAll;
|
||||||
|
|
||||||
|
@OneToOne
|
||||||
|
private Leaf none;
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Leaf get(String field) {
|
||||||
|
return switch (field) {
|
||||||
|
case "onPersist" -> onPersist;
|
||||||
|
case "onMerge" -> onMerge;
|
||||||
|
case "onRemove" -> onRemove;
|
||||||
|
case "onRefresh" -> onRefresh;
|
||||||
|
case "onDetach" -> onDetach;
|
||||||
|
case "onAll" -> onAll;
|
||||||
|
case "none" -> none;
|
||||||
|
default -> throw new IllegalArgumentException(field);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void set(String field, Leaf leaf) {
|
||||||
|
switch (field) {
|
||||||
|
case "onPersist" -> onPersist = leaf;
|
||||||
|
case "onMerge" -> onMerge = leaf;
|
||||||
|
case "onRemove" -> onRemove = leaf;
|
||||||
|
case "onRefresh" -> onRefresh = leaf;
|
||||||
|
case "onDetach" -> onDetach = leaf;
|
||||||
|
case "onAll" -> onAll = leaf;
|
||||||
|
case "none" -> none = leaf;
|
||||||
|
default -> throw new IllegalArgumentException(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Profile {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String bio;
|
||||||
|
|
||||||
|
protected Profile() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Profile(String bio) {
|
||||||
|
this.bio = bio;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
/** The startup's mapping: cascade = ALL on a @ManyToOne to a shared parent. Do not copy. */
|
||||||
|
@Entity
|
||||||
|
public class ProjectBad {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||||
|
@JoinColumn(name = "owner_id")
|
||||||
|
private AppUser owner;
|
||||||
|
|
||||||
|
protected ProjectBad() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProjectBad(String title, AppUser owner) {
|
||||||
|
this.title = title;
|
||||||
|
this.owner = owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
import org.hibernate.annotations.OnDelete;
|
||||||
|
import org.hibernate.annotations.OnDeleteAction;
|
||||||
|
|
||||||
|
/** The same bad mapping on a schema whose foreign key says ON DELETE CASCADE: the "worst case" of the incident. */
|
||||||
|
@Entity
|
||||||
|
public class ProjectBadDb {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||||
|
@JoinColumn(name = "owner_id")
|
||||||
|
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||||
|
private AppUser owner;
|
||||||
|
|
||||||
|
protected ProjectBadDb() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProjectBadDb(String title, AppUser owner) {
|
||||||
|
this.title = title;
|
||||||
|
this.owner = owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
/** The fix: no cascade on the shared parent. The user's lifecycle is independent of any one project. */
|
||||||
|
@Entity
|
||||||
|
public class ProjectGood {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
// No cascade: the AppUser lifecycle is independent of the project lifecycle
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "owner_id")
|
||||||
|
private AppUser owner;
|
||||||
|
|
||||||
|
protected ProjectGood() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProjectGood(String title, AppUser owner) {
|
||||||
|
this.title = title;
|
||||||
|
this.owner = owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
|
/** Independent of any course: a student keeps an account and other enrolments when one course disappears. */
|
||||||
|
@Entity
|
||||||
|
public class Student {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
protected Student() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
/** The one legitimate use of cascade on a @ManyToOne: creating the parent in the same unit of work as its first child. Never REMOVE. */
|
||||||
|
@Entity
|
||||||
|
public class Ticket {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String subject;
|
||||||
|
|
||||||
|
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||||
|
private Agent agent;
|
||||||
|
|
||||||
|
protected Ticket() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Ticket(String subject, Agent agent) {
|
||||||
|
this.subject = subject;
|
||||||
|
this.agent = agent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.hibernate.annotations.OnDelete;
|
||||||
|
import org.hibernate.annotations.OnDeleteAction;
|
||||||
|
|
||||||
|
/** The common idiom: JPA cascade = REMOVE together with @OnDelete, so Hibernate cascades in memory and leaves the row deletes to the database. */
|
||||||
|
@Entity
|
||||||
|
public class Vault {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "vault", cascade = CascadeType.ALL)
|
||||||
|
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||||
|
private List<VaultEntry> entries = new ArrayList<>();
|
||||||
|
|
||||||
|
public VaultEntry add(String memo) {
|
||||||
|
VaultEntry e = new VaultEntry(this, memo);
|
||||||
|
entries.add(e);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<VaultEntry> getEntries() {
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class VaultEntry {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String memo;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "vault_id")
|
||||||
|
private Vault vault;
|
||||||
|
|
||||||
|
protected VaultEntry() {
|
||||||
|
}
|
||||||
|
|
||||||
|
VaultEntry(Vault vault, String memo) {
|
||||||
|
this.vault = vault;
|
||||||
|
this.memo = memo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Cascade ALL on the owned children is correct: a writer's comments die with the writer's account. */
|
||||||
|
@Entity
|
||||||
|
public class Writer {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "author",
|
||||||
|
cascade = CascadeType.ALL,
|
||||||
|
orphanRemoval = true)
|
||||||
|
private List<Comment> comments = new ArrayList<>();
|
||||||
|
|
||||||
|
protected Writer() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Writer(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Comment comment(String text) {
|
||||||
|
Comment c = new Comment(this, text);
|
||||||
|
comments.add(c);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Comment> getComments() {
|
||||||
|
return comments;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
import org.hibernate.boot.MetadataSources;
|
||||||
|
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||||
|
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||||
|
import org.hibernate.resource.jdbc.spi.StatementInspector;
|
||||||
|
|
||||||
|
/** Plain Hibernate bootstrap on an in-memory H2 (no Spring, no persistence.xml) plus helpers that record the SQL Hibernate sends. */
|
||||||
|
final class Db implements AutoCloseable {
|
||||||
|
|
||||||
|
/** Every SQL string Hibernate prepares, in order (raw JDBC issued by the tests is not recorded). */
|
||||||
|
private static final List<String> LOG = new ArrayList<>();
|
||||||
|
|
||||||
|
public static class Recorder implements StatementInspector {
|
||||||
|
@Override
|
||||||
|
public String inspect(String sql) {
|
||||||
|
synchronized (LOG) {
|
||||||
|
LOG.add(sql.replaceAll("\\s+", " ").trim());
|
||||||
|
}
|
||||||
|
return sql;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final SessionFactory sf;
|
||||||
|
|
||||||
|
private Db(SessionFactory sf) {
|
||||||
|
this.sf = sf;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Db open(Class<?>... entities) {
|
||||||
|
return open(Map.of(), entities);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Db open(Map<String, String> extra, Class<?>... entities) {
|
||||||
|
StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder()
|
||||||
|
.applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1")
|
||||||
|
.applySetting("hibernate.connection.username", "sa")
|
||||||
|
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
|
||||||
|
.applySetting("hibernate.generate_statistics", "true")
|
||||||
|
.applySetting("hibernate.session_factory.statement_inspector", Recorder.class.getName());
|
||||||
|
extra.forEach(b::applySetting);
|
||||||
|
StandardServiceRegistry registry = b.build();
|
||||||
|
MetadataSources sources = new MetadataSources(registry);
|
||||||
|
for (Class<?> e : entities) {
|
||||||
|
sources.addAnnotatedClass(e);
|
||||||
|
}
|
||||||
|
return new Db(sources.buildMetadata().buildSessionFactory());
|
||||||
|
}
|
||||||
|
|
||||||
|
SessionFactory sf() {
|
||||||
|
return sf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs {@code work} in its own session and transaction. */
|
||||||
|
<T> T tx(Function<Session, T> work) {
|
||||||
|
try (Session s = sf.openSession()) {
|
||||||
|
var t = s.beginTransaction();
|
||||||
|
try {
|
||||||
|
T r = work.apply(s);
|
||||||
|
t.commit();
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
if (t.isActive()) {
|
||||||
|
t.rollback();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void txv(Consumer<Session> work) {
|
||||||
|
tx(s -> {
|
||||||
|
work.accept(s);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs the action and returns the SQL Hibernate prepared while it ran. */
|
||||||
|
static List<String> sql(Runnable action) {
|
||||||
|
synchronized (LOG) {
|
||||||
|
LOG.clear();
|
||||||
|
}
|
||||||
|
action.run();
|
||||||
|
synchronized (LOG) {
|
||||||
|
return new ArrayList<>(LOG);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw JDBC query, each row rendered as {@code a | b | c}. */
|
||||||
|
List<String> rows(String sql) {
|
||||||
|
return tx(s -> s.doReturningWork(cn -> {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
try (var st = cn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
|
||||||
|
ResultSetMetaData md = rs.getMetaData();
|
||||||
|
while (rs.next()) {
|
||||||
|
StringBuilder b = new StringBuilder();
|
||||||
|
for (int i = 1; i <= md.getColumnCount(); i++) {
|
||||||
|
if (i > 1) {
|
||||||
|
b.append(" | ");
|
||||||
|
}
|
||||||
|
b.append(rs.getObject(i));
|
||||||
|
}
|
||||||
|
out.add(b.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw JDBC statement (DDL or DML), invisible to the SQL recorder. */
|
||||||
|
void exec(String sql) {
|
||||||
|
txv(s -> s.doWork(cn -> {
|
||||||
|
try (var st = cn.createStatement()) {
|
||||||
|
st.execute(sql);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
long count(String table) {
|
||||||
|
return Long.parseLong(rows("select count(*) from " + table).get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The foreign keys of one table with their ON DELETE rule, straight from H2's information schema. */
|
||||||
|
List<String> foreignKeys(String table) {
|
||||||
|
return rows("select tc.constraint_name, rc.delete_rule from information_schema.table_constraints tc "
|
||||||
|
+ "join information_schema.referential_constraints rc on rc.constraint_name = tc.constraint_name "
|
||||||
|
+ "and rc.constraint_schema = tc.constraint_schema "
|
||||||
|
+ "where tc.table_name = '" + table.toUpperCase() + "' and tc.constraint_type = 'FOREIGN KEY' order by 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
static Throwable root(Throwable t) {
|
||||||
|
while (t.getCause() != null && t.getCause() != t) {
|
||||||
|
t = t.getCause();
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exception chain on one line, class names only, so transcripts stay stable. */
|
||||||
|
static String chain(Throwable t) {
|
||||||
|
StringBuilder sb = new StringBuilder(t.getClass().getName());
|
||||||
|
Throwable c = t.getCause();
|
||||||
|
while (c != null && c != t) {
|
||||||
|
sb.append(" <- ").append(c.getClass().getName());
|
||||||
|
t = c;
|
||||||
|
c = c.getCause();
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String firstLine(Throwable t) {
|
||||||
|
return String.valueOf(t.getMessage()).lines().findFirst().orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (sf.isOpen()) {
|
||||||
|
sf.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Which cascade types exist in the shipped jars, which of them are deprecated, and which internal classes really do the walking. */
|
||||||
|
class T01_ApiShapeTest {
|
||||||
|
|
||||||
|
private static String exists(String className) {
|
||||||
|
try {
|
||||||
|
Class.forName(className);
|
||||||
|
return "present";
|
||||||
|
}
|
||||||
|
catch (ClassNotFoundException e) {
|
||||||
|
return "absent";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String deprecation(Class<?> c) {
|
||||||
|
Deprecated d = c.getAnnotation(Deprecated.class);
|
||||||
|
return d == null ? "not deprecated" : "deprecated(since=" + d.since() + ", forRemoval=" + d.forRemoval() + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiShape() {
|
||||||
|
Transcript t = new Transcript("01-api-shape", "Cascade API shape in the shipped jars");
|
||||||
|
|
||||||
|
t.heading("jakarta.persistence.CascadeType constants");
|
||||||
|
var jpa = Arrays.stream(jakarta.persistence.CascadeType.values()).map(Enum::name).toList();
|
||||||
|
t.line(String.join(", ", jpa));
|
||||||
|
|
||||||
|
t.heading("org.hibernate.annotations.CascadeType (Hibernate's own enum)");
|
||||||
|
Class<?> hcs = classOrNull("org.hibernate.annotations.CascadeType");
|
||||||
|
t.line("enum class: " + (hcs == null ? "absent" : "present, " + deprecation(hcs)));
|
||||||
|
String hibernateConstants = "n/a";
|
||||||
|
if (hcs != null) {
|
||||||
|
hibernateConstants = Arrays.stream(hcs.getEnumConstants()).map(Object::toString).toList().toString();
|
||||||
|
t.line("constants: " + hibernateConstants);
|
||||||
|
boolean lock = Arrays.stream(hcs.getFields()).map(Field::getName).anyMatch("LOCK"::equals);
|
||||||
|
t.line("has LOCK: " + lock);
|
||||||
|
}
|
||||||
|
Class<?> cascade = classOrNull("org.hibernate.annotations.Cascade");
|
||||||
|
t.line("@Cascade annotation: " + (cascade == null ? "absent" : "present, " + deprecation(cascade)));
|
||||||
|
|
||||||
|
t.heading("Internal classes that do the cascading (where each lives in this jar)");
|
||||||
|
for (String c : new String[] {"Cascade", "CascadingAction", "CascadingActions", "CascadeStyle", "CascadeStyles", "CascadePoint"}) {
|
||||||
|
t.line(String.format("%-18s org.hibernate.engine.internal/spi: %-8s org.hibernate.cascade.internal/spi: %s", c,
|
||||||
|
exists("org.hibernate.engine.internal." + c).equals("present") || exists("org.hibernate.engine.spi." + c).equals("present") ? "present" : "absent",
|
||||||
|
exists("org.hibernate.cascade.internal." + c).equals("present") || exists("org.hibernate.cascade.spi." + c).equals("present") ? "present" : "absent"));
|
||||||
|
}
|
||||||
|
t.line("CascadeEntityPersister (a name the old article used): " + exists("org.hibernate.persister.entity.CascadeEntityPersister"));
|
||||||
|
t.write();
|
||||||
|
assertThat(jpa).containsExactly("ALL", "PERSIST", "MERGE", "REMOVE", "REFRESH", "DETACH");
|
||||||
|
assertThat(exists("org.hibernate.persister.entity.CascadeEntityPersister")).isEqualTo("absent");
|
||||||
|
if (Transcript.LABEL.equals("h7")) {
|
||||||
|
assertThat(exists("org.hibernate.engine.internal.Cascade")).isEqualTo("present");
|
||||||
|
assertThat(hcs).isNotNull();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
assertThat(exists("org.hibernate.cascade.internal.Cascade")).isEqualTo("present");
|
||||||
|
assertThat(hcs).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Class<?> classOrNull(String n) {
|
||||||
|
try {
|
||||||
|
return Class.forName(n);
|
||||||
|
}
|
||||||
|
catch (ClassNotFoundException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** The smallest working example: invoice + lines with cascade ALL and orphanRemoval. The SQL for persist, unlink one line, and remove. */
|
||||||
|
class T02_CompositionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void invoiceOwnsItsLines() {
|
||||||
|
Transcript t = new Transcript("02-composition", "Composition: Invoice -> InvoiceLine, cascade = ALL + orphanRemoval = true");
|
||||||
|
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||||
|
t.heading("persist(invoice) with two new lines, lines never persisted explicitly");
|
||||||
|
Long id = db.tx(s -> {
|
||||||
|
Invoice inv = new Invoice("INV-1");
|
||||||
|
inv.addLine("hosting");
|
||||||
|
inv.addLine("support");
|
||||||
|
var sql = Db.sql(() -> {
|
||||||
|
s.persist(inv);
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
t.step("persist(inv); flush()", sql);
|
||||||
|
assertThat(sql).hasSize(3);
|
||||||
|
return inv.getId();
|
||||||
|
});
|
||||||
|
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
assertThat(db.count("InvoiceLine")).isEqualTo(2);
|
||||||
|
|
||||||
|
t.heading("remove one line from the collection (the invoice stays)");
|
||||||
|
t.step("lines.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
Invoice inv = s.find(Invoice.class, id);
|
||||||
|
inv.getLines().remove(0);
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
assertThat(db.count("invoice")).isEqualTo(1);
|
||||||
|
assertThat(db.count("InvoiceLine")).isEqualTo(1);
|
||||||
|
|
||||||
|
t.heading("remove the invoice");
|
||||||
|
t.step("remove(find(Invoice)); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Invoice.class, id));
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
assertThat(db.count("invoice")).isZero();
|
||||||
|
assertThat(db.count("InvoiceLine")).isZero();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** cascade = REMOVE and orphanRemoval = true fire on different triggers. Three mappings, two triggers. */
|
||||||
|
class T03_OrphanVsRemoveTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unlinkingAChild() {
|
||||||
|
Transcript t = new Transcript("03-orphan-vs-remove", "orphanRemoval vs cascade = REMOVE");
|
||||||
|
try (Db db = Db.open(Basket.class, BasketItem.class, Folder.class, Doc.class, Invoice.class, InvoiceLine.class)) {
|
||||||
|
|
||||||
|
t.heading("Trigger 1: child removed from the parent's collection, parent kept");
|
||||||
|
Long basketId = db.tx(s -> {
|
||||||
|
Basket b = new Basket();
|
||||||
|
b.add("keyboard");
|
||||||
|
b.add("mouse");
|
||||||
|
s.persist(b);
|
||||||
|
return b.getId();
|
||||||
|
});
|
||||||
|
t.step("Basket (cascade = {PERSIST, REMOVE}, no orphanRemoval): items.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.find(Basket.class, basketId).getItems().remove(0);
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: BasketItem=" + db.count("BasketItem") + " (still 2: nothing was deleted)");
|
||||||
|
assertThat(db.count("BasketItem")).isEqualTo(2);
|
||||||
|
|
||||||
|
Long invoiceId = db.tx(s -> {
|
||||||
|
Invoice inv = new Invoice("INV-7");
|
||||||
|
inv.addLine("a");
|
||||||
|
inv.addLine("b");
|
||||||
|
s.persist(inv);
|
||||||
|
return inv.getId();
|
||||||
|
});
|
||||||
|
t.step("Invoice (cascade = ALL, orphanRemoval = true): lines.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.find(Invoice.class, invoiceId).getLines().remove(0);
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine") + " (now 1: the orphan was deleted)");
|
||||||
|
assertThat(db.count("InvoiceLine")).isEqualTo(1);
|
||||||
|
|
||||||
|
t.heading("Trigger 2: the parent itself is removed");
|
||||||
|
Long folderId = db.tx(s -> {
|
||||||
|
Folder f = new Folder();
|
||||||
|
f.add("a");
|
||||||
|
f.add("b");
|
||||||
|
s.persist(f);
|
||||||
|
return f.getId();
|
||||||
|
});
|
||||||
|
t.line("Folder maps cascade = PERSIST and orphanRemoval = true, and has no REMOVE at all");
|
||||||
|
t.step("remove(folder); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Folder.class, folderId));
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: doc=" + db.count("doc") + " (0: orphanRemoval alone also deletes children when the parent goes)");
|
||||||
|
assertThat(db.count("doc")).isZero();
|
||||||
|
|
||||||
|
t.step("Basket (REMOVE, no orphanRemoval): remove(basket); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Basket.class, basketId));
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: BasketItem=" + db.count("BasketItem") + " basket=" + db.count("basket"));
|
||||||
|
assertThat(db.count("BasketItem")).isZero();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** The startup incident, reproduced: cascade = ALL on a @ManyToOne to a shared parent, in the three ways it plays out. */
|
||||||
|
class T04_IncidentTest {
|
||||||
|
|
||||||
|
/** Runs the action, returns the exception it threw (or null) and records the SQL Hibernate prepared meanwhile. */
|
||||||
|
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||||
|
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||||
|
var sql = Db.sql(() -> {
|
||||||
|
try {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
thrown.set(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
t.step(label, sql);
|
||||||
|
if (thrown.get() != null) {
|
||||||
|
t.line(" threw: " + Db.chain(thrown.get()));
|
||||||
|
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||||
|
}
|
||||||
|
return thrown.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cascadeAllOnManyToOne() {
|
||||||
|
Transcript t = new Transcript("04-incident", "The incident: cascade = ALL on a @ManyToOne to a shared parent");
|
||||||
|
try (Db db = Db.open(AppUser.class, ProjectBad.class, ProjectBadDb.class, ProjectGood.class)) {
|
||||||
|
|
||||||
|
t.heading("Foreign keys on the project tables (ON DELETE rule as H2 reports it)");
|
||||||
|
t.line("ProjectBad : " + db.foreignKeys("ProjectBad"));
|
||||||
|
t.line("ProjectBadDb : " + db.foreignKeys("ProjectBadDb"));
|
||||||
|
t.line("ProjectGood : " + db.foreignKeys("ProjectGood"));
|
||||||
|
assertThat(db.foreignKeys("ProjectBadDb").get(0)).contains("CASCADE");
|
||||||
|
assertThat(db.foreignKeys("ProjectBad").get(0)).doesNotContain("CASCADE");
|
||||||
|
|
||||||
|
t.heading("1. Testing: every project has its own user");
|
||||||
|
Long pid1 = db.tx(s -> {
|
||||||
|
AppUser u = new AppUser("test-user-1");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectBad p = new ProjectBad("p1", u);
|
||||||
|
s.persist(p);
|
||||||
|
return p.getId();
|
||||||
|
});
|
||||||
|
Throwable e1 = run(t, "remove(project 1); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(ProjectBad.class, pid1));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: AppUser=" + db.count("AppUser") + " ProjectBad=" + db.count("ProjectBad") + " (the user is gone, nothing failed)");
|
||||||
|
assertThat(e1).isNull();
|
||||||
|
assertThat(db.count("AppUser")).isZero();
|
||||||
|
|
||||||
|
t.heading("2. Production, plain schema: the user has two projects");
|
||||||
|
Long pid2 = db.tx(s -> {
|
||||||
|
AppUser u = new AppUser("real-user");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectBad a = new ProjectBad("first", u);
|
||||||
|
ProjectBad b = new ProjectBad("second", u);
|
||||||
|
s.persist(a);
|
||||||
|
s.persist(b);
|
||||||
|
return a.getId();
|
||||||
|
});
|
||||||
|
Throwable e2 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(ProjectBad.class, pid2));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows after rollback: AppUser=" + db.count("AppUser") + " ProjectBad=" + db.count("ProjectBad"));
|
||||||
|
assertThat(e2).isNotNull();
|
||||||
|
assertThat(db.count("ProjectBad")).isEqualTo(2);
|
||||||
|
|
||||||
|
t.heading("3. Production, schema with ON DELETE CASCADE on the foreign key");
|
||||||
|
Long pid3 = db.tx(s -> {
|
||||||
|
AppUser u = new AppUser("real-user-db");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectBadDb a = new ProjectBadDb("first", u);
|
||||||
|
ProjectBadDb b = new ProjectBadDb("second", u);
|
||||||
|
s.persist(a);
|
||||||
|
s.persist(b);
|
||||||
|
return a.getId();
|
||||||
|
});
|
||||||
|
t.line("before: ProjectBadDb=" + db.count("ProjectBadDb"));
|
||||||
|
Throwable e3 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(ProjectBadDb.class, pid3));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: ProjectBadDb=" + db.count("ProjectBadDb") + " (both projects gone, no error)");
|
||||||
|
assertThat(e3).isNull();
|
||||||
|
assertThat(db.count("ProjectBadDb")).isZero();
|
||||||
|
|
||||||
|
t.heading("4. The fix: ProjectGood, no cascade");
|
||||||
|
long usersBefore = db.count("AppUser");
|
||||||
|
Long pid4 = db.tx(s -> {
|
||||||
|
AppUser u = new AppUser("real-user-good");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectGood a = new ProjectGood("first", u);
|
||||||
|
ProjectGood b = new ProjectGood("second", u);
|
||||||
|
s.persist(a);
|
||||||
|
s.persist(b);
|
||||||
|
return a.getId();
|
||||||
|
});
|
||||||
|
Throwable e4 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(ProjectGood.class, pid4));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: ProjectGood=" + db.count("ProjectGood") + " AppUser=" + (db.count("AppUser") - usersBefore) + " new user(s) kept");
|
||||||
|
assertThat(e4).isNull();
|
||||||
|
assertThat(db.count("ProjectGood")).isEqualTo(1);
|
||||||
|
assertThat(db.count("AppUser") - usersBefore).isEqualTo(1);
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badAndImprovedComment() {
|
||||||
|
Transcript t = new Transcript("04b-comment-author", "Bad -> improved: CommentBad (cascade ALL to the author) vs Comment + Writer.comments");
|
||||||
|
try (Db db = Db.open(Writer.class, Comment.class, CommentBad.class)) {
|
||||||
|
|
||||||
|
t.heading("Bad: a writer with two comments, delete one");
|
||||||
|
Long cid = db.tx(s -> {
|
||||||
|
Writer w = new Writer("ann");
|
||||||
|
s.persist(w);
|
||||||
|
CommentBad a = new CommentBad(w, "first");
|
||||||
|
s.persist(a);
|
||||||
|
s.persist(new CommentBad(w, "second"));
|
||||||
|
return a.getId();
|
||||||
|
});
|
||||||
|
Throwable e = run(t, "remove(CommentBad first); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(CommentBad.class, cid));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
t.line("raw rows after rollback: Writer=" + db.count("Writer") + " CommentBad=" + db.count("CommentBad"));
|
||||||
|
|
||||||
|
t.heading("Improved: cascade flows down from Writer to Comment, never up");
|
||||||
|
Long wid = db.tx(s -> {
|
||||||
|
Writer w = new Writer("bob");
|
||||||
|
w.comment("one");
|
||||||
|
w.comment("two");
|
||||||
|
s.persist(w);
|
||||||
|
return w.getId();
|
||||||
|
});
|
||||||
|
Long first = db.rows("select min(id) from Comment").get(0).equals("null") ? null : Long.parseLong(db.rows("select min(id) from Comment").get(0));
|
||||||
|
Throwable e2 = run(t, "remove(Comment one); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Comment.class, first));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Writer(bob)=" + db.rows("select count(*) from Writer where name = 'bob'").get(0) + " Comment=" + db.count("Comment"));
|
||||||
|
assertThat(e2).isNull();
|
||||||
|
assertThat(db.count("Comment")).isEqualTo(1);
|
||||||
|
|
||||||
|
run(t, "remove(Writer bob); flush() (cascade ALL downward)", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Writer.class, wid));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Comment=" + db.count("Comment"));
|
||||||
|
assertThat(db.count("Comment")).isZero();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** One test per relationship type in the decision tree: @ManyToMany, @OneToOne, and the one legitimate cascade on a @ManyToOne. */
|
||||||
|
class T05_RelationshipsTest {
|
||||||
|
|
||||||
|
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||||
|
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||||
|
var sql = Db.sql(() -> {
|
||||||
|
try {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
thrown.set(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
t.step(label, sql);
|
||||||
|
if (thrown.get() != null) {
|
||||||
|
t.line(" threw: " + Db.chain(thrown.get()));
|
||||||
|
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||||
|
}
|
||||||
|
return thrown.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void manyToMany() {
|
||||||
|
Transcript t = new Transcript("05a-many-to-many", "@ManyToMany: cascade ALL vs {PERSIST, MERGE}");
|
||||||
|
try (Db db = Db.open(Student.class, CourseBad.class, CourseGood.class)) {
|
||||||
|
|
||||||
|
t.heading("CourseBad (cascade = ALL): one student enrolled in two courses");
|
||||||
|
Long bad1 = db.tx(s -> {
|
||||||
|
Student shared = new Student("shared");
|
||||||
|
CourseBad a = new CourseBad("algebra");
|
||||||
|
CourseBad b = new CourseBad("biology");
|
||||||
|
a.getStudents().add(shared);
|
||||||
|
b.getStudents().add(shared);
|
||||||
|
s.persist(a);
|
||||||
|
s.persist(b);
|
||||||
|
return a.getId();
|
||||||
|
});
|
||||||
|
Throwable e = run(t, "remove(algebra); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(CourseBad.class, bad1));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
t.line("raw rows after rollback: CourseBad=" + db.count("CourseBad") + " Student=" + db.count("Student"));
|
||||||
|
|
||||||
|
t.heading("CourseBad: the same, but the student is only in that one course");
|
||||||
|
Long bad2 = db.tx(s -> {
|
||||||
|
CourseBad c = new CourseBad("chemistry");
|
||||||
|
c.getStudents().add(new Student("solo"));
|
||||||
|
s.persist(c);
|
||||||
|
return c.getId();
|
||||||
|
});
|
||||||
|
long studentsBefore = db.count("Student");
|
||||||
|
Throwable e2 = run(t, "remove(chemistry); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(CourseBad.class, bad2));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
assertThat(e2).isNull();
|
||||||
|
t.line("raw rows: Student " + studentsBefore + " -> " + db.count("Student") + " (the student was deleted with the course)");
|
||||||
|
assertThat(db.count("Student")).isEqualTo(studentsBefore - 1);
|
||||||
|
|
||||||
|
t.heading("CourseGood (cascade = {PERSIST, MERGE})");
|
||||||
|
Long good = db.tx(s -> {
|
||||||
|
CourseGood c = new CourseGood("dance");
|
||||||
|
c.getStudents().add(new Student("d1"));
|
||||||
|
c.getStudents().add(new Student("d2"));
|
||||||
|
s.persist(c);
|
||||||
|
return c.getId();
|
||||||
|
});
|
||||||
|
long before = db.count("Student");
|
||||||
|
run(t, "remove(dance); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(CourseGood.class, good));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Student " + before + " -> " + db.count("Student") + " course_good_students=" + db.count("course_good_students"));
|
||||||
|
assertThat(db.count("Student")).isEqualTo(before);
|
||||||
|
assertThat(db.count("course_good_students")).isZero();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oneToOne() {
|
||||||
|
Transcript t = new Transcript("05b-one-to-one", "@OneToOne: an owned profile cascades, a shared address does not");
|
||||||
|
try (Db db = Db.open(Person.class, Profile.class, Address.class)) {
|
||||||
|
|
||||||
|
t.heading("Persisting a person with a new profile and a new, unsaved address");
|
||||||
|
Throwable e = run(t, "persist(person); flush()", () -> db.txv(s -> {
|
||||||
|
Person p = new Person("zed");
|
||||||
|
p.setProfile(new Profile("owned"));
|
||||||
|
p.setBillingAddress(new Address("1 Main St"));
|
||||||
|
s.persist(p);
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
t.line("raw rows after rollback: Person=" + db.count("Person") + " Profile=" + db.count("Profile"));
|
||||||
|
|
||||||
|
t.heading("Same, with the shared address persisted first");
|
||||||
|
Long pid = db.tx(s -> {
|
||||||
|
Address a = new Address("1 Main St");
|
||||||
|
s.persist(a);
|
||||||
|
Person p = new Person("zed");
|
||||||
|
p.setProfile(new Profile("owned"));
|
||||||
|
p.setBillingAddress(a);
|
||||||
|
s.persist(p);
|
||||||
|
return p.getId();
|
||||||
|
});
|
||||||
|
t.line("raw rows: Person=" + db.count("Person") + " Profile=" + db.count("Profile") + " Address=" + db.count("Address"));
|
||||||
|
assertThat(db.count("Profile")).isEqualTo(1);
|
||||||
|
|
||||||
|
run(t, "setProfile(null); flush() (orphanRemoval)", () -> db.txv(s -> {
|
||||||
|
s.find(Person.class, pid).setProfile(null);
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Profile=" + db.count("Profile"));
|
||||||
|
assertThat(db.count("Profile")).isZero();
|
||||||
|
|
||||||
|
db.txv(s -> s.find(Person.class, pid).setProfile(new Profile("again")));
|
||||||
|
run(t, "remove(person); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Person.class, pid));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Person=" + db.count("Person") + " Profile=" + db.count("Profile") + " Address=" + db.count("Address") + " (the address survives)");
|
||||||
|
assertThat(db.count("Profile")).isZero();
|
||||||
|
assertThat(db.count("Address")).isEqualTo(1);
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void manyToOnePersistAndMerge() {
|
||||||
|
Transcript t = new Transcript("05c-many-to-one", "@ManyToOne with cascade = {PERSIST, MERGE}: what it is for, and what it cannot do");
|
||||||
|
try (Db db = Db.open(Ticket.class, Agent.class)) {
|
||||||
|
|
||||||
|
t.heading("New parent created together with its first child");
|
||||||
|
run(t, "persist(new Ticket(.., new Agent())); flush()", () -> db.txv(s -> {
|
||||||
|
s.persist(new Ticket("printer", new Agent("new-agent")));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||||
|
assertThat(db.count("Agent")).isEqualTo(1);
|
||||||
|
|
||||||
|
t.heading("Parent already exists (a detached Agent): persist vs merge");
|
||||||
|
Agent detached = db.tx(s -> {
|
||||||
|
Agent a = new Agent("existing");
|
||||||
|
s.persist(a);
|
||||||
|
return a;
|
||||||
|
});
|
||||||
|
Throwable e = run(t, "persist(new Ticket(.., detachedAgent)); flush()", () -> db.txv(s -> {
|
||||||
|
s.persist(new Ticket("scanner", detached));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
run(t, "merge(new Ticket(.., detachedAgent)); flush()", () -> db.txv(s -> {
|
||||||
|
s.merge(new Ticket("scanner", detached));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||||
|
assertThat(db.count("Ticket")).isEqualTo(2);
|
||||||
|
assertThat(db.count("Agent")).isEqualTo(2);
|
||||||
|
|
||||||
|
t.heading("Removing a ticket never touches its agent");
|
||||||
|
Long id = Long.parseLong(db.rows("select min(id) from Ticket").get(0));
|
||||||
|
run(t, "remove(ticket); flush()", () -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Ticket.class, id));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||||
|
assertThat(db.count("Agent")).isEqualTo(2);
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** What cascade = REMOVE costs, how a bulk delete changes that, and what a database-level ON DELETE CASCADE leaves behind in memory. */
|
||||||
|
class T06_UnderTheHoodTest {
|
||||||
|
|
||||||
|
static final int N = 1000;
|
||||||
|
|
||||||
|
private static long count(List<String> sql, String prefix) {
|
||||||
|
return sql.stream().filter(s -> s.startsWith(prefix)).count();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Long invoiceWithLines(Db db) {
|
||||||
|
return db.tx(s -> {
|
||||||
|
Invoice inv = new Invoice("BIG");
|
||||||
|
for (int i = 0; i < N; i++) {
|
||||||
|
inv.addLine("line " + i);
|
||||||
|
}
|
||||||
|
s.persist(inv);
|
||||||
|
return inv.getId();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cascadeRemoveVersusBulkDelete() {
|
||||||
|
Transcript t = new Transcript("06a-cascade-remove-cost", "Removing an invoice with " + N + " lines: cascade REMOVE vs bulk delete first");
|
||||||
|
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||||
|
|
||||||
|
t.line("effective hibernate.jdbc.batch_size: " + db.sf().unwrap(org.hibernate.engine.spi.SessionFactoryImplementor.class).getSessionFactoryOptions().getJdbcBatchSize());
|
||||||
|
t.heading("A. em.remove(invoice) with cascade = ALL, lines never touched by the code");
|
||||||
|
Long a = invoiceWithLines(db);
|
||||||
|
int[] managed = new int[2];
|
||||||
|
db.sf().getStatistics().clear();
|
||||||
|
var sqlA = Db.sql(() -> db.txv(s -> {
|
||||||
|
Invoice inv = s.find(Invoice.class, a);
|
||||||
|
managed[0] = s.getStatistics().getEntityCount();
|
||||||
|
s.remove(inv);
|
||||||
|
managed[1] = s.getStatistics().getEntityCount();
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("entities in the persistence context after find(): " + managed[0]);
|
||||||
|
t.line("entities in the persistence context after remove(): " + managed[1]);
|
||||||
|
long deletedA = db.sf().getStatistics().getEntityDeleteCount();
|
||||||
|
t.line("entities deleted (Hibernate statistics): " + deletedA);
|
||||||
|
t.line("SQL strings prepared: total=" + sqlA.size() + " select=" + count(sqlA, "select") + " delete=" + count(sqlA, "delete"));
|
||||||
|
t.line("first statements:");
|
||||||
|
sqlA.stream().limit(4).forEach(s -> t.line(" sql> " + s));
|
||||||
|
assertThat(managed[0]).isEqualTo(1);
|
||||||
|
assertThat(managed[1]).isEqualTo(N + 1);
|
||||||
|
assertThat(deletedA).isEqualTo(N + 1);
|
||||||
|
if (Transcript.LABEL.equals("h7")) {
|
||||||
|
assertThat(count(sqlA, "delete")).isEqualTo(N + 1);
|
||||||
|
}
|
||||||
|
assertThat(db.count("InvoiceLine")).isZero();
|
||||||
|
|
||||||
|
t.heading("A2. the same removal with hibernate.flush.queue.type=legacy (ignored by 7.x)");
|
||||||
|
try (Db legacy = Db.open(Map.of("hibernate.flush.queue.type", "legacy"), Invoice.class, InvoiceLine.class)) {
|
||||||
|
Long a2 = invoiceWithLines(legacy);
|
||||||
|
var sqlA2 = Db.sql(() -> legacy.txv(s -> {
|
||||||
|
s.remove(s.find(Invoice.class, a2));
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("SQL strings prepared: total=" + sqlA2.size() + " select=" + count(sqlA2, "select") + " delete=" + count(sqlA2, "delete"));
|
||||||
|
assertThat(legacy.count("InvoiceLine")).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
t.heading("B. bulk delete of the lines first, then remove(getReference(invoice))");
|
||||||
|
Long b = invoiceWithLines(db);
|
||||||
|
int[] managedB = new int[1];
|
||||||
|
db.sf().getStatistics().clear();
|
||||||
|
var sqlB = Db.sql(() -> db.txv(s -> {
|
||||||
|
s.createMutationQuery("delete from InvoiceLine l where l.invoice.id = :id").setParameter("id", b).executeUpdate();
|
||||||
|
Invoice ref = s.getReference(Invoice.class, b);
|
||||||
|
s.remove(ref);
|
||||||
|
managedB[0] = s.getStatistics().getEntityCount();
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("entities in the persistence context after remove(): " + managedB[0]);
|
||||||
|
t.line("entities deleted (Hibernate statistics): " + db.sf().getStatistics().getEntityDeleteCount());
|
||||||
|
t.line("SQL strings prepared: total=" + sqlB.size() + " select=" + count(sqlB, "select") + " delete=" + count(sqlB, "delete"));
|
||||||
|
sqlB.forEach(s -> t.line(" sql> " + s));
|
||||||
|
assertThat(db.count("Invoice")).isZero();
|
||||||
|
assertThat(db.count("InvoiceLine")).isZero();
|
||||||
|
assertThat(sqlB).hasSize(4);
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Throwable attempt(Runnable r) {
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void databaseCascade() {
|
||||||
|
Transcript t = new Transcript("06b-on-delete-cascade", "@OnDelete(CASCADE): the database deletes the children, Hibernate does not know");
|
||||||
|
try (Db db = Db.open(Ledger.class, LedgerEntry.class, Vault.class, VaultEntry.class, AppUser.class, ProjectGood.class)) {
|
||||||
|
t.line("LedgerEntry foreign key: " + db.foreignKeys("LedgerEntry"));
|
||||||
|
t.line("VaultEntry foreign key: " + db.foreignKeys("VaultEntry"));
|
||||||
|
|
||||||
|
t.heading("1. Ledger: @OnDelete only, children never loaded");
|
||||||
|
Long l1 = db.tx(s -> {
|
||||||
|
Ledger l = new Ledger();
|
||||||
|
l.add("a");
|
||||||
|
l.add("b");
|
||||||
|
l.add("c");
|
||||||
|
s.persist(l);
|
||||||
|
// no JPA cascade on Ledger.entries, so every child is persisted by hand
|
||||||
|
l.getEntries().forEach(s::persist);
|
||||||
|
return l.getId();
|
||||||
|
});
|
||||||
|
t.step("remove(find(Ledger)); flush()", Db.sql(() -> db.txv(s -> {
|
||||||
|
s.remove(s.find(Ledger.class, l1));
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.line("raw rows: Ledger=" + db.count("Ledger") + " LedgerEntry=" + db.count("LedgerEntry"));
|
||||||
|
assertThat(db.count("LedgerEntry")).isZero();
|
||||||
|
|
||||||
|
t.heading("2. Ledger: @OnDelete only, but the entries are already loaded in the session");
|
||||||
|
Long l2 = db.tx(s -> {
|
||||||
|
Ledger l = new Ledger();
|
||||||
|
l.add("a");
|
||||||
|
l.add("b");
|
||||||
|
s.persist(l);
|
||||||
|
l.getEntries().forEach(s::persist);
|
||||||
|
return l.getId();
|
||||||
|
});
|
||||||
|
Throwable[] thrown = new Throwable[1];
|
||||||
|
var sql2 = Db.sql(() -> thrown[0] = attempt(() -> db.txv(s -> {
|
||||||
|
Ledger l = s.find(Ledger.class, l2);
|
||||||
|
l.getEntries().size();
|
||||||
|
s.remove(l);
|
||||||
|
s.flush();
|
||||||
|
})));
|
||||||
|
t.step("find(Ledger); entries.size(); remove(ledger); flush()", sql2);
|
||||||
|
t.line(" threw: " + Db.chain(thrown[0]));
|
||||||
|
t.line(" cause: " + Db.firstLine(Db.root(thrown[0])));
|
||||||
|
assertThat(thrown[0]).isNotNull();
|
||||||
|
|
||||||
|
t.heading("3. Vault: cascade = ALL plus @OnDelete, entries loaded");
|
||||||
|
Long v = db.tx(s -> {
|
||||||
|
Vault vault = new Vault();
|
||||||
|
vault.add("a");
|
||||||
|
vault.add("b");
|
||||||
|
vault.add("c");
|
||||||
|
s.persist(vault);
|
||||||
|
return vault.getId();
|
||||||
|
});
|
||||||
|
try (var s = db.sf().openSession()) {
|
||||||
|
var tx = s.beginTransaction();
|
||||||
|
Vault vault = s.find(Vault.class, v);
|
||||||
|
VaultEntry first = vault.getEntries().get(0);
|
||||||
|
Long firstId = first.getId();
|
||||||
|
var sql3 = Db.sql(() -> {
|
||||||
|
s.remove(vault);
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
t.step("find(Vault); remove(vault); flush()", sql3);
|
||||||
|
tx.commit();
|
||||||
|
t.line("raw rows after commit: Vault=" + db.count("Vault") + " VaultEntry=" + db.count("VaultEntry"));
|
||||||
|
t.line("same session, contains(firstEntry) after commit: " + s.contains(first));
|
||||||
|
t.line("same session, find(VaultEntry " + "first" + "): " + (s.find(VaultEntry.class, firstId) == null ? "null" : "still returns an entity"));
|
||||||
|
assertThat(sql3).anyMatch(x -> x.startsWith("delete from Vault "));
|
||||||
|
assertThat(db.count("VaultEntry")).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
t.heading("4. A cascade that only exists in the schema: the mapping (ProjectGood -> AppUser) says nothing about it");
|
||||||
|
String fk = db.rows("select constraint_name from information_schema.table_constraints where table_name = 'PROJECTGOOD' and constraint_type = 'FOREIGN KEY'").get(0);
|
||||||
|
db.exec("alter table ProjectGood drop constraint " + fk);
|
||||||
|
db.exec("alter table ProjectGood add constraint fk_project_owner foreign key (owner_id) references AppUser (id) on delete cascade");
|
||||||
|
t.line("ProjectGood foreign key now: " + db.foreignKeys("ProjectGood"));
|
||||||
|
Long[] ids = db.tx(s -> {
|
||||||
|
AppUser u = new AppUser("schema-cascade");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectGood p = new ProjectGood("p", u);
|
||||||
|
s.persist(p);
|
||||||
|
return new Long[] {u.getId(), p.getId()};
|
||||||
|
});
|
||||||
|
try (var s = db.sf().openSession()) {
|
||||||
|
var tx = s.beginTransaction();
|
||||||
|
AppUser u = s.find(AppUser.class, ids[0]);
|
||||||
|
ProjectGood p = s.find(ProjectGood.class, ids[1]);
|
||||||
|
var sql4 = Db.sql(() -> s.createNativeMutationQuery("delete from AppUser where id = ?1").setParameter(1, ids[0]).executeUpdate());
|
||||||
|
t.step("native: delete from AppUser where id = ?", sql4);
|
||||||
|
tx.commit();
|
||||||
|
t.line("raw rows: AppUser(id)=" + db.rows("select count(*) from AppUser where id = " + ids[0]).get(0) + " ProjectGood(id)=" + db.rows("select count(*) from ProjectGood where id = " + ids[1]).get(0));
|
||||||
|
var sql5 = Db.sql(() -> t.line("same session, find(ProjectGood) -> " + (s.find(ProjectGood.class, ids[1]) == null ? "null" : "still returns the deleted project")));
|
||||||
|
t.line("SQL issued by that find: " + sql5.size());
|
||||||
|
t.line("same session, contains(project): " + s.contains(p));
|
||||||
|
assertThat(s.contains(p)).isTrue();
|
||||||
|
assertThat(sql5).isEmpty();
|
||||||
|
s.clear();
|
||||||
|
t.line("after session.clear(), find(ProjectGood) -> " + (s.find(ProjectGood.class, ids[1]) == null ? "null" : "entity"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Ways orphanRemoval goes wrong: replacing the collection object, and merge() on a parent whose collection was emptied. */
|
||||||
|
class T07_OrphanFailureModesTest {
|
||||||
|
|
||||||
|
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||||
|
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||||
|
var sql = Db.sql(() -> {
|
||||||
|
try {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
thrown.set(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
t.step(label, sql);
|
||||||
|
if (thrown.get() != null) {
|
||||||
|
t.line(" threw: " + Db.chain(thrown.get()));
|
||||||
|
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||||
|
}
|
||||||
|
return thrown.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Long invoice(Db db, String number, int lines) {
|
||||||
|
return db.tx(s -> {
|
||||||
|
Invoice inv = new Invoice(number);
|
||||||
|
for (int i = 0; i < lines; i++) {
|
||||||
|
inv.addLine("l" + i);
|
||||||
|
}
|
||||||
|
s.persist(inv);
|
||||||
|
return inv.getId();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void replacingTheCollection() {
|
||||||
|
Transcript t = new Transcript("07a-replace-collection", "orphanRemoval: replacing the collection instead of changing it");
|
||||||
|
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||||
|
Long id = invoice(db, "R-1", 2);
|
||||||
|
|
||||||
|
t.heading("setLines(new ArrayList<>()) on a managed invoice");
|
||||||
|
Throwable e = run(t, "setLines(new ArrayList<>()); flush()", () -> db.txv(s -> {
|
||||||
|
s.find(Invoice.class, id).setLines(new ArrayList<>());
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows after rollback: InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
assertThat(db.count("InvoiceLine")).isEqualTo(2);
|
||||||
|
|
||||||
|
t.heading("The safe way: clear() the existing collection");
|
||||||
|
Throwable ok = run(t, "getLines().clear(); flush()", () -> db.txv(s -> {
|
||||||
|
s.find(Invoice.class, id).getLines().clear();
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
assertThat(ok).isNull();
|
||||||
|
assertThat(db.count("InvoiceLine")).isZero();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mergeOfAnEmptiedCollection() {
|
||||||
|
Transcript t = new Transcript("07b-merge-emptied-collection", "orphanRemoval and merge(): managed parent, emptied collection (reported as a 6.6 -> 7.x regression)");
|
||||||
|
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||||
|
|
||||||
|
t.heading("1. managed invoice, getLines().clear(), merge(invoice), flush()");
|
||||||
|
Long id1 = invoice(db, "M-1", 2);
|
||||||
|
Throwable e1 = run(t, "clear(); merge(inv); flush()", () -> db.txv(s -> {
|
||||||
|
Invoice inv = s.find(Invoice.class, id1);
|
||||||
|
inv.getLines().clear();
|
||||||
|
s.merge(inv);
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine"));
|
||||||
|
|
||||||
|
t.heading("2. managed invoice, clear(), add one new line, merge(invoice), flush()");
|
||||||
|
long before = db.count("InvoiceLine");
|
||||||
|
Long id2 = invoice(db, "M-2", 2);
|
||||||
|
Throwable e2 = run(t, "clear(); addLine(); merge(inv); flush()", () -> db.txv(s -> {
|
||||||
|
Invoice inv = s.find(Invoice.class, id2);
|
||||||
|
inv.getLines().clear();
|
||||||
|
inv.addLine("replacement");
|
||||||
|
s.merge(inv);
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows for invoice M-2 lines: " + db.rows("select description from InvoiceLine where invoice_id = " + id2));
|
||||||
|
|
||||||
|
t.heading("3. the normal detached round trip: load, close session, remove a line, merge in a new session");
|
||||||
|
Long id3 = invoice(db, "M-3", 3);
|
||||||
|
Invoice detached = db.tx(s -> {
|
||||||
|
Invoice inv = s.find(Invoice.class, id3);
|
||||||
|
inv.getLines().size();
|
||||||
|
return inv;
|
||||||
|
});
|
||||||
|
detached.getLines().remove(0);
|
||||||
|
Throwable e3 = run(t, "merge(detachedInvoice); flush()", () -> db.txv(s -> {
|
||||||
|
s.merge(detached);
|
||||||
|
s.flush();
|
||||||
|
}));
|
||||||
|
t.line("raw rows for invoice M-3 lines: " + db.rows("select count(*) from InvoiceLine where invoice_id = " + id3));
|
||||||
|
assertThat(e3).isNull();
|
||||||
|
assertThat(db.rows("select count(*) from InvoiceLine where invoice_id = " + id3)).containsExactly("2");
|
||||||
|
t.line("outcomes: 1=" + (e1 == null ? "ok" : "threw") + " 2=" + (e2 == null ? "ok" : "threw") + " 3=" + (e3 == null ? "ok" : "threw"));
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Two entities with no cascade between them are removed in the "wrong" order. Hibernate 8's graph-based flush is meant to plan deletes from the foreign keys. */
|
||||||
|
class T08_DeleteOrderTest {
|
||||||
|
|
||||||
|
private static String scenario(Map<String, String> settings, Transcript t, boolean mandatory) {
|
||||||
|
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||||
|
AtomicReference<java.util.List<String>> sqlRef = new AtomicReference<>(java.util.List.of());
|
||||||
|
try (Db db = Db.open(settings, AppUser.class, ProjectGood.class, Board.class, Card.class)) {
|
||||||
|
Long[] ids = db.tx(s -> {
|
||||||
|
if (mandatory) {
|
||||||
|
Board b = new Board("order-test");
|
||||||
|
s.persist(b);
|
||||||
|
Card c = new Card("c", b);
|
||||||
|
s.persist(c);
|
||||||
|
return new Long[] {b.getId(), c.getId()};
|
||||||
|
}
|
||||||
|
AppUser u = new AppUser("order-test");
|
||||||
|
s.persist(u);
|
||||||
|
ProjectGood p = new ProjectGood("p", u);
|
||||||
|
s.persist(p);
|
||||||
|
return new Long[] {u.getId(), p.getId()};
|
||||||
|
});
|
||||||
|
var sql = Db.sql(() -> {
|
||||||
|
try {
|
||||||
|
db.txv(s -> {
|
||||||
|
Object parent = mandatory ? s.find(Board.class, ids[0]) : s.find(AppUser.class, ids[0]);
|
||||||
|
Object child = mandatory ? s.find(Card.class, ids[1]) : s.find(ProjectGood.class, ids[1]);
|
||||||
|
s.remove(parent); // parent first ...
|
||||||
|
s.remove(child); // ... then the child that still points at it
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
thrown.set(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
sqlRef.set(sql);
|
||||||
|
t.step("remove(parent); remove(child); flush()", sql);
|
||||||
|
if (thrown.get() != null) {
|
||||||
|
t.line(" threw: " + Db.chain(thrown.get()));
|
||||||
|
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||||
|
}
|
||||||
|
t.line("raw rows: parent=" + db.count(mandatory ? "Board" : "AppUser") + " child=" + db.count(mandatory ? "Card" : "ProjectGood"));
|
||||||
|
}
|
||||||
|
String firstDelete = sqlRef.get().stream().filter(x -> x.startsWith("delete from ")).findFirst().map(x -> x.split(" ")[2]).orElse("none");
|
||||||
|
return (thrown.get() == null ? "ok" : "threw") + "/first delete: " + firstDelete;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteOrder() {
|
||||||
|
Transcript t = new Transcript("08-delete-order", "Deleting a parent and its (non-cascaded) child in one flush, parent removed first");
|
||||||
|
String[] out = new String[4];
|
||||||
|
int i = 0;
|
||||||
|
for (boolean mandatory : new boolean[] {false, true}) {
|
||||||
|
t.heading(mandatory ? "Card.board is optional = false (the foreign key cannot be nulled)" : "ProjectGood.owner is nullable");
|
||||||
|
t.line("-- default settings");
|
||||||
|
out[i++] = scenario(Map.of(), t, mandatory);
|
||||||
|
t.line("-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)");
|
||||||
|
out[i++] = scenario(Map.of("hibernate.flush.queue.type", "legacy"), t, mandatory);
|
||||||
|
}
|
||||||
|
t.line("");
|
||||||
|
t.line("outcomes: nullable default=" + out[0] + " | nullable legacy=" + out[1] + " | mandatory default=" + out[2] + " | mandatory legacy=" + out[3]);
|
||||||
|
t.write();
|
||||||
|
boolean h7 = Transcript.LABEL.equals("h7");
|
||||||
|
assertThat(out[0]).isEqualTo(h7 ? "ok/first delete: AppUser" : "ok/first delete: ProjectGood");
|
||||||
|
assertThat(out[1]).isEqualTo("ok/first delete: AppUser");
|
||||||
|
assertThat(out[2]).startsWith("threw");
|
||||||
|
assertThat(out[3]).startsWith("threw");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Which JPA operation travels along which cascade type: five operations against seven one-to-one associations to the same Leaf entity. */
|
||||||
|
class T09_CascadeMatrixTest {
|
||||||
|
|
||||||
|
static final List<String> FIELDS = List.of("onPersist", "onMerge", "onRemove", "onRefresh", "onDetach", "onAll", "none");
|
||||||
|
|
||||||
|
/** A probe whose only association is {@code field}, with the leaf already saved, and the ids of both. */
|
||||||
|
private static Long[] saved(Db db, String field) {
|
||||||
|
return db.tx(s -> {
|
||||||
|
Leaf leaf = new Leaf("original");
|
||||||
|
s.persist(leaf);
|
||||||
|
Probe p = new Probe();
|
||||||
|
p.set(field, leaf);
|
||||||
|
s.persist(p);
|
||||||
|
return new Long[] {p.getId(), leaf.getId()};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean persistTravels(Db db, String field) {
|
||||||
|
try {
|
||||||
|
db.txv(s -> {
|
||||||
|
Probe p = new Probe();
|
||||||
|
p.set(field, new Leaf("new"));
|
||||||
|
s.persist(p);
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean mergeTravels(Db db, String field) {
|
||||||
|
Long[] ids = saved(db, field);
|
||||||
|
Probe detached = db.tx(s -> s.find(Probe.class, ids[0]));
|
||||||
|
detached.get(field).setLabel("changed in detached copy");
|
||||||
|
db.txv(s -> {
|
||||||
|
s.merge(detached);
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
return db.rows("select label from Leaf where id = " + ids[1]).get(0).equals("changed in detached copy");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean removeTravels(Db db, String field) {
|
||||||
|
Long[] ids = saved(db, field);
|
||||||
|
try {
|
||||||
|
db.txv(s -> {
|
||||||
|
s.remove(s.find(Probe.class, ids[0]));
|
||||||
|
s.flush();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (RuntimeException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return db.rows("select count(*) from Leaf where id = " + ids[1]).get(0).equals("0");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean refreshTravels(Db db, String field) {
|
||||||
|
Long[] ids = saved(db, field);
|
||||||
|
return db.tx(s -> {
|
||||||
|
Probe p = s.find(Probe.class, ids[0]);
|
||||||
|
Leaf leaf = p.get(field);
|
||||||
|
s.doWork(cn -> {
|
||||||
|
try (var st = cn.createStatement()) {
|
||||||
|
st.execute("update Leaf set label = 'changed in the database' where id = " + ids[1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
s.refresh(p);
|
||||||
|
return leaf.getLabel().equals("changed in the database");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean detachTravels(Db db, String field) {
|
||||||
|
Long[] ids = saved(db, field);
|
||||||
|
return db.tx(s -> {
|
||||||
|
Probe p = s.find(Probe.class, ids[0]);
|
||||||
|
Leaf leaf = p.get(field);
|
||||||
|
s.detach(p);
|
||||||
|
return !s.contains(leaf);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matrix() {
|
||||||
|
Transcript t = new Transcript("09-cascade-matrix", "Which operation propagates along which cascade type (one @OneToOne per type, all to Leaf)");
|
||||||
|
try (Db db = Db.open(Probe.class, Leaf.class)) {
|
||||||
|
String[] ops = {"persist", "merge", "remove", "refresh", "detach"};
|
||||||
|
List<List<String>> travelled = new ArrayList<>();
|
||||||
|
for (String op : ops) {
|
||||||
|
List<String> hit = new ArrayList<>();
|
||||||
|
for (String f : FIELDS) {
|
||||||
|
boolean yes = switch (op) {
|
||||||
|
case "persist" -> persistTravels(db, f);
|
||||||
|
case "merge" -> mergeTravels(db, f);
|
||||||
|
case "remove" -> removeTravels(db, f);
|
||||||
|
case "refresh" -> refreshTravels(db, f);
|
||||||
|
default -> detachTravels(db, f);
|
||||||
|
};
|
||||||
|
if (yes) {
|
||||||
|
hit.add(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
travelled.add(hit);
|
||||||
|
t.line(String.format("%-8s propagates along: %s", op + "()", hit));
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
assertThat(travelled.get(0)).containsExactly("onPersist", "onAll");
|
||||||
|
assertThat(travelled.get(1)).containsExactly("onMerge", "onAll");
|
||||||
|
assertThat(travelled.get(2)).containsExactly("onRemove", "onAll");
|
||||||
|
assertThat(travelled.get(3)).containsExactly("onRefresh", "onAll");
|
||||||
|
assertThat(travelled.get(4)).containsExactly("onDetach", "onAll");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.ankurm.cascade;
|
||||||
|
|
||||||
|
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-<label>.txt (label = h7 or h8); the tests assert the same facts. */
|
||||||
|
final class Transcript {
|
||||||
|
|
||||||
|
static final String LABEL = System.getProperty("h.label", "h7");
|
||||||
|
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 + "-" + LABEL + ".txt");
|
||||||
|
line("# " + title);
|
||||||
|
line("# Hibernate ORM " + VERSION + ", H2, JDK " + Runtime.version().feature());
|
||||||
|
}
|
||||||
|
|
||||||
|
Transcript line(String s) {
|
||||||
|
lines.add(s);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Transcript heading(String s) {
|
||||||
|
line("");
|
||||||
|
return line("== " + s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user