JPA Cascade Types in Hibernate 7: A Decision Tree (Because the Wrong One Will Delete Your Data)
JPA cascade types in Hibernate 7.4 explained from scratch: which type belongs on which relationship, how orphanRemoval differs from REMOVE, the cascade = ALL on @ManyToOne incident reproduced with real SQL, the cost of cascading over 1000 children, @OnDelete, and what Hibernate 8 changes.
A startup wrote cascade = CascadeType.ALL on a @ManyToOne from Project to its owner. The idea was sensible: deleting a project should clean up after itself. In testing every project had its own user, so it worked. In production a user had several projects, and deleting one of them deleted the user. Four hours of restoring a backup followed. This post shows exactly how that happens, with the SQL from a real run, and gives you a way to choose a cascade type without guessing.
If you are meeting the topic for the first time: a cascade tells Hibernate “when I do this to the parent, do the same to its children”. By the end you will know the six JPA cascade types, which one belongs on which relationship, how orphanRemoval differs from REMOVE, what a cascade costs when a parent has a thousand children, and what Hibernate 8 changes.
Versions tested. Hibernate ORM 7.4.15.Final (the latest 7.x GA in maven-metadata.xml when this was written), Jakarta Persistence 3.2.0, H2 2.4.240 in memory, plain Hibernate with no Spring, JDK Temurin 25. Hibernate 8.0.0.CR1 is a release candidate, not GA; it was run too, and where it differs the post says so. Every SQL line and number below comes from a file in the companion repository’s output folder, regenerated by run-all.sh. H2 is not your production database: the shape of the SQL (which statements, how many) transfers; constraint messages and generated names will differ.
A cascade copies one operation from a parent to its children
Without a cascade, em.persist(invoice) saves the invoice and nothing else. If the invoice holds two new line objects, Hibernate refuses to flush because they are unsaved. With cascade = PERSIST on the lines, the same one call saves all three. That is all a cascade is: a per-association instruction that says which of the five lifecycle calls (persist, merge, remove, refresh, detach) should also be applied to the objects on the other side.
The picture shows the one rule everything else builds on: a cascade follows an arrow from an entity to the entities it points at, and only for the operation you named. The six constants you can name are in the table.
Type
Fires when you call
What it does to the child
PERSIST
em.persist(parent)
Makes new children managed and inserts them
MERGE
em.merge(parent)
Copies detached child state onto managed children
REMOVE
em.remove(parent)
Schedules the children for deletion
REFRESH
em.refresh(parent)
Reloads the children from the database
DETACH
em.detach(parent)
Removes the children from the persistence context
ALL
any of the above
All five at once
Hibernate-only LOCK
session.lock(parent)
Existed in org.hibernate.annotations.CascadeType; see the Hibernate 8 section
The first six rows are the constants in jakarta.persistence.CascadeType. The seventh is not JPA: it lives in Hibernate’s own enum, which is deprecated for removal in 7.x and gone in 8. The jar inspection that proves this is 01-api-shape-h7.txt (7.4.15) and 01-api-shape-h8.txt (8.0.0.CR1). A second test confirms the table above: each of the five operations travels only along its own cascade type and ALL, never along the others (09-cascade-matrix-h7.txt).
== jakarta.persistence.CascadeType constants
ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
Going deeper: which operation travels along which type
The matrix test maps one association per cascade type to the same child and calls each operation in turn. The result is exactly the table: persist() propagates along [onPersist, onAll], merge() along [onMerge, onAll], and so on, and no operation propagates along none. In practice this means cascade = REMOVE never makes a persist cascade, which is why people who copy {PERSIST, REMOVE} from a snippet should know what each half does.
The smallest useful cascade: an invoice that owns its lines
An invoice line has no life without its invoice, so the invoice should be able to create and delete its lines. That is composition, and it is the case where cascade = ALL with orphanRemoval = true is correct. The mapping, from Invoice.java (the line class is InvoiceLine.java):
The test persists an invoice with two new lines and never touches the lines directly. The log is in 02-composition-h7.txt:
-- 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
One persist call, three inserts. Removing the invoice shows the other direction:
-- 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
Notice the second statement: before it can delete the lines, Hibernate selects them. Keep that in mind; it is the reason a cascade gets expensive later in this post.
Going deeper: why the order is lines first, parent last
A line carries the foreign key to its invoice, so the invoice row cannot be deleted while a line still points at it. Hibernate cascades the remove to the children first and then deletes the parent, which is what the log shows. The full test is T02_CompositionTest.java.
Which cascade for which relationship: a decision tree
The question to ask is always the same: does this entity own the other one’s lifecycle, or does it merely point at something shared? Ownership flows downward from parent to child. Cascade should only ever follow that direction.
The tree is a summary of the four sections below. Each one backs its rule with a test that actually removes something and records what Hibernate did.
@OneToMany: composition versus aggregation
The invoice above is composition. When the children are independent (they can be shared, reassigned or kept after the parent is gone) it is aggregation, and REMOVE does not belong on it. Use {PERSIST, MERGE} at most. If you also want children unlinked from the collection to be deleted, that is orphanRemoval, covered in the next section.
@ManyToOne: almost never
The “many” side points at a shared parent, so cascading REMOVE upward from it is how the incident at the top happened. The one legitimate use is {PERSIST, MERGE} when you create a new parent together with its first child. The mapping is Ticket.java:
The behaviour is in 05c-many-to-one-h7.txt. It works for a new parent, it fails with a detached parent on persist, and it works with merge:
-- persist(new Ticket(.., new Agent())); flush()
sql> insert into Agent (name,id) values (?,default)
sql> insert into Ticket (agent_id,subject,id) values (?,?,default)
-- 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)
Removing the ticket afterwards leaves its agent untouched, as the same transcript shows. A PERSIST cascade on a @ManyToOne is therefore a convenience for creation, never for deletion.
@OneToOne: depends on ownership
A profile that only makes sense attached to one person is owned: ALL plus orphanRemoval. A billing address shared by several people is not: no cascade. Person.java has one of each:
From 05b-one-to-one-h7.txt: persisting a person whose billing address was never saved fails, because nothing cascades to it; setting the profile to null deletes the profile row; removing the person deletes the profile but leaves the 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
-- remove(person); flush()
sql> delete from Person where id=?
sql> delete from Profile where id=?
raw rows: Person=0 Profile=0 Address=1 (the address survives)
@ManyToMany: never cascade REMOVE
With many-to-many both sides are independent: a student can be in several courses. CourseBad.java cascades ALL to students; CourseGood.java cascades {PERSIST, MERGE} only. The three outcomes are in 05a-many-to-many-h7.txt:
== CourseBad (cascade = ALL): one student enrolled in two courses
-- remove(algebra); flush()
sql> delete from course_bad_students where course_id=?
sql> delete from Student where id=?
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
raw rows after rollback: CourseBad=2 Student=1
== CourseBad: the same, but the student is only in that one course
raw rows: Student 2 -> 1 (the student was deleted with the course)
== CourseGood (cascade = {PERSIST, MERGE})
-- remove(dance); flush()
sql> delete from course_good_students where course_id=?
sql> delete from CourseGood where id=?
raw rows: Student 3 -> 3 course_good_students=0
Two things to take from it. A shared student makes the delete fail loudly (a constraint violation); a student in only that course is deleted silently, so the same code passes one test and breaks another. With {PERSIST, MERGE} only the join rows go, and all three students remain.
Going deeper: the long tail for each relationship
The four relationship tests share one file, T05_RelationshipsTest.java. For the rest of each mapping (bidirectional helper methods, Set versus List, the join-table choices) the existing posts go further than a cascade post should:
Both delete children, but they fire on different events. REMOVE fires when the parent is removed. orphanRemoval fires when a child is unlinked from the parent’s collection, and (as the test shows) when the parent is removed too.
Event
cascade = REMOVE
orphanRemoval = true
Parent removed with em.remove()
Children deleted
Children deleted
Child taken out of the collection, parent kept
Nothing deleted, the row stays
The child row is deleted at flush
The second row is the classic source of leftover rows: removing an item from a list and expecting it to disappear from the database. 03-orphan-vs-remove-h7.txt puts the two side by side, using Basket.java ({PERSIST, REMOVE}, no orphan removal) against the invoice:
-- Basket (cascade = {PERSIST, REMOVE}, no orphanRemoval): items.remove(0); flush()
raw rows: BasketItem=2 (still 2: nothing was deleted)
-- Invoice (cascade = ALL, orphanRemoval = true): lines.remove(0); flush()
sql> delete from InvoiceLine where id=?
raw rows: InvoiceLine=1 (now 1: the orphan was deleted)
One more detail the table hides: orphanRemoval alone, with no REMOVE at all, still deletes the children when the parent is removed. Folder.java maps cascade = PERSIST and orphanRemoval = true, and removing a folder deleted both of its documents.
The fingerprint of this bug. Rows that stay behind after the application removed them from a list, with no error anywhere. Check whether the mapping has orphanRemoval = true, not just cascade = REMOVE.
Two ways orphanRemoval fails in practice
orphanRemoval tracks the specific collection object Hibernate gave the entity. Replace that object and Hibernate cannot follow what became of the old one. The setter test is 07a-replace-collection-h7.txt:
-- setLines(new ArrayList<>()); flush()
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> delete from InvoiceLine where id=?
sql> delete from InvoiceLine where id=?
raw rows: InvoiceLine=0
The rule: change the existing collection (clear(), add(), remove()), never assign a new one to a managed parent.
Going deeper: a reported merge() regression I could not reproduce
A forum report describes merge() on a parent with an emptied orphanRemoval collection deleting nothing on 7.2.19 (the issue key quoted there is HHH-20670). I tried the three plausible shapes on 7.4.15 and on 8.0.0.CR1: emptying a managed collection and merging; emptying, adding one new line and merging; and the ordinary detached round trip. All three deleted the right rows, so the evidence here is not reproducible on these versions. It says nothing about 7.2.19, and I did not test that release. The transcript is 07b-merge-emptied-collection-h7.txt:
The project service calls em.remove(project). The same code produced four different outcomes depending on the data and the schema. All four are in 04-incident-h7.txt:
Outcome 3 is the one that happened to the startup. The diagram is the argument: a mapping that passes your tests can still be wrong, because the test data hid the second project.
== 1. Testing: every project has its own user
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
sql> delete from ProjectBad where id=?
sql> delete from AppUser where id=?
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
raw rows after rollback: AppUser=1 ProjectBad=2
== 3. Production, schema with ON DELETE CASCADE on the foreign key
raw rows: ProjectBadDb=0 (both projects gone, no error)
== 4. The fix: ProjectGood, no cascade
sql> delete from ProjectGood where id=?
raw rows: ProjectGood=1 AppUser=1 new user(s) kept
Outcome 3 uses ProjectBadDb.java, the same mapping with @OnDelete(action = CASCADE), which makes the foreign key itself cascade. The fix is ProjectGood.java, which is the same class without the cascade attribute.
Bad → improved. The same mistake with comments: deleting a comment cascades to its author. In 04b-comment-author-h7.txt a writer with two comments cannot lose one comment without a constraint violation. The improved mapping puts the cascade on the writer (parent to children), never on the comment (child to shared parent):
== Bad: a writer with two comments, delete one
sql> delete from CommentBad where id=?
sql> delete from Writer where id=?
threw: org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException
raw rows after rollback: Writer=1 CommentBad=2
== Improved: cascade flows down from Writer to Comment, never up
-- remove(Comment one); flush()
sql> delete from Comment where id=?
raw rows: Writer(bob)=1 Comment=1
The improved classes are Writer.java (cascade ALL with orphanRemoval on its comments) and Comment.java. (The original version of this post described the incident as two SQL statements; the real log has a select and then two deletes.)
The rule to remember. Cascade belongs on the side that owns the lifecycle and walks downward. It must never bubble upward from a child to a shared parent.
Going deeper: why a foreign key made it worse
Outcomes 2 and 3 differ only in the foreign key rule that H2 reports: NO ACTION for ProjectBad.java and CASCADE for ProjectBadDb.java. With NO ACTION the database protects you by refusing the delete. With ON DELETE CASCADE it does what Hibernate asked and then some, which is why the “works fine in the schema we have” argument is not a defence. Test: T04_IncidentTest.java.
What a cascade costs: one parent, a thousand children
Remember that select of the lines before deleting an invoice. Hibernate cannot cascade REMOVE to children it has not loaded, so it loads all of them, makes each a managed entity, and deletes them. 06a-cascade-remove-cost-h7.txt measures an invoice with 1000 lines:
== 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
One call, 1001 managed entities, 1001 prepared delete statements. The fix is to delete the children in one statement first and then remove the parent through a reference, so the lines never enter the persistence context:
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);
== 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
Four statements instead of 1003. Two of them are still selects, because remove on a reference loads the invoice and its (now empty) line collection. (The original version of this post called it “two statements”; the measured count is four.)
Trade-off. A bulk delete bypasses lifecycle callbacks and cascades on the children. Use it for rows with no hooks, and check your own SQL log: the numbers above are statement counts on H2, not timings.
Letting the database cascade: @OnDelete
The other way to avoid the load is to let the database delete children with ON DELETE CASCADE, which Hibernate can generate with @OnDelete. It is one DELETE, but Hibernate does not know about the children that vanished, and the session can disagree with the database. Four scenarios in 06b-on-delete-cascade-h7.txt, built on Ledger.java (@OnDelete only) and Vault.java (cascade = ALL plus @OnDelete):
== 1. Ledger: @OnDelete only, children never loaded
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
threw: java.lang.IllegalStateException <- org.hibernate.TransientPropertyValueException
== 3. Vault: cascade = ALL plus @OnDelete, entries loaded
sql> delete from Vault where id=?
raw rows after commit: Vault=0 VaultEntry=0
same session, find(VaultEntry first): null
== 4. A cascade that only exists in the schema: the mapping (ProjectGood -> AppUser) says nothing about it
same session, find(ProjectGood) -> still returns the deleted project
SQL issued by that find: 0
after session.clear(), find(ProjectGood) -> null
Read it as a ladder. @OnDelete alone is fine only while the children are not loaded (1) and throws if they are (2). Combined with cascade = ALL it works and the session stays consistent (3). And a cascade that exists only in the schema leaves the session holding an entity that no longer exists (4), until you clear it.
Going deeper: the order of deletes when nothing is cascaded
If you remove a parent and a non-cascaded child in the same flush, does Hibernate delete the child first? It depends on the version and on whether the foreign key is nullable. 08-delete-order-h7.txt and 08-delete-order-h8.txt record it:
Scenario
7.4.15
8.0.0.CR1 default
8.0.0.CR1 legacy queue
Nullable foreign key
updates the FK to null, deletes the parent first
updates the FK, deletes the child first
same as 7.x
Mandatory foreign key (optional = false)
PropertyValueException
PropertyValueException
PropertyValueException
The mandatory case throws before any delete is issued, on both versions and both queue settings. The practical lesson: remove the child before the parent, and do not rely on flush order.
Hibernate 8.0.0.CR1 is a release candidate, not a GA release, so treat this section as a preview and re-check at GA. Everything in this post ran on it too (01-api-shape-h8.txt). What I found by inspecting the jar and running the same tests:
Hibernate’s own @Cascade annotation and org.hibernate.annotations.CascadeType enum are gone. In 7.4.15 both are deprecated for removal; the enum still holds LOCK, REPLICATE and DELETE_ORPHAN beyond the JPA constants.
The cascade engine classes moved from org.hibernate.engine.internal/spi to org.hibernate.cascade.internal/spi. Application code should not touch these.
Graph-based flushing is the default. For the 1000-line invoice, 8.0.0.CR1 prepares 4 statements (batched, still 1001 entities deleted) against 1003 on 7.4.15. hibernate.flush.queue.type=legacy restores the old behaviour and the 1003 count.
Per the 8.0 migration guide for CR1, custom CascadeStyle and CascadingAction implementations are unsupported, and the Hibernate-specific lock cascade is removed.
The first bullet is why the table at the top marks LOCK as Hibernate-only. If you use the Hibernate @Cascade annotation today, the 7.x deprecation warnings are your migration list.
Going deeper: running the module on Hibernate 8
The module is standalone. The default build uses 7.4.15; to run on the release candidate:
mvn -B clean test -Dhibernate.version=8.0.0.CR1 -Dpersistence.version=4.0.0-M8 -Dh.label=h8
This needs clean between runs: classes compiled against one Jakarta Persistence API link wrongly against the other. run-all.sh does both runs and writes every transcript, -h7 and -h8. Build file: pom.xml.
Often, no. Cascade REMOVE is a convenience that hides a delete behind an innocent-looking em.remove(). Reserve ALL plus orphanRemoval for true composition (the invoice and its lines, a person and their profile), where the children are small in number. For anything shared, or with thousands of children, delete explicitly: a bulk DELETE, or a service method that says what it removes. Everything here is H2 and plain Hibernate with counts, not timings; measure on your own database before choosing.
Frequently asked questions
Should I always use cascade = ALL on @OneToMany?
Only for true composition, where the child has no meaningful existence outside the parent. For independent children use {PERSIST, MERGE} at most and never cascade REMOVE.
What is the difference between cascade REMOVE and database ON DELETE CASCADE?
REMOVE runs in the application: Hibernate loads the children and issues the deletes, so lifecycle callbacks run and the session stays consistent. ON DELETE CASCADE runs in the database and Hibernate does not see it, so a session can keep entities that no longer exist (scenario 4 above, 06b-on-delete-cascade-h7.txt).
Why does my cascade = ALL cause an OutOfMemoryError on delete?
Cascading REMOVE loads every child as a managed entity first (1001 for the 1000-line invoice above). With very large collections that is a lot of heap. Delete the children with one bulk statement before removing the parent (06a-cascade-remove-cost-h7.txt). I measured entity and statement counts here, not memory use, so the heap claim is the mechanism, not a measurement.
Conclusion
Choosing a cascade type is a modelling decision that Hibernate then enforces mechanically. Ask who owns whose lifecycle. If the parent owns the child, cascade downward: ALL with orphanRemoval for composition. If the child points at something shared, do not cascade at all. Know that orphanRemoval covers the case REMOVE misses (unlinking a child), watch the cost of cascading over large collections, and remember that the database schema decides whether a bad mapping fails loudly or deletes your users.
No Comments yet!