Skip to lesson

Cascade types and orphanRemoval

An order has three items, and saving each one by hand is noise. Yet a cascade on the wrong link deletes data you wanted to keep.

CascadeType: PERSIST, MERGE, REMOVE and ALL

A cascade passes an operation from a parent entity to its linked children: with cascade = CascadeType.ALL, saving the order saves its items and deleting the order deletes them. Use it only when the child lives and dies with the parent.

An order item exists only inside its order, so one orders.save(order) should save both. Compare the same save with and without cascade.

What orders.save(order) sends. With cascade = ALL on Order.items, it inserts the order first and then one insert into order_items for each item, so the items get the new order id. With no cascade, only the order is inserted and the items are never saved, with no error.

Example 1 · Order.items with cascade ALL: one save for the order and its items

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/main/java/com/shoplite/lab/order/Order.java (the collection)@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)@OrderBy("id")private List<OrderItem> items = new ArrayList<>();
// src/main/java/com/shoplite/lab/order/CascadeLabService.java/** One save() for the order; cascade PERSIST saves the items. */@Transactionalpublic void placeOrder() {    Product book = products.findById(9).orElseThrow();    Product earbuds = products.findById(6).orElseThrow();    Order order = new Order(1, 1, LocalDateTime.of(2026, 10, 16, 11, 42));    order.addItem(new OrderItem(book, 1, book.getPrice()));    order.addItem(new OrderItem(earbuds, 2, earbuds.getPrice()));    orders.save(order);    System.out.println("Saved order " + order.getId() + " with " + order.getItems().size()            + " items, total " + order.total());}
Output (each run on a fresh database)
--- Run 1: cascade = CascadeType.ALL
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG SQL - insert into orders (address_id,customer_id,ordered_at,status) values (?,?,?,?)
DEBUG SQL - insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)
DEBUG SQL - insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)
Saved order 17 with 2 items, total 3097.00
--- Run 2: @OneToMany(mappedBy = "order") with no cascade
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG SQL - insert into orders (address_id,customer_id,ordered_at,status) values (?,?,?,?)
Saved order 17 with 2 items, total 3097.00
SELECT COUNT(*) AS items_of_order_17 FROM order_items WHERE order_id = 17;
+-------------------+
| items_of_order_17 |
+-------------------+
|                 0 |
+-------------------+

What this code does

  • There is no orderItems.save(...): cascade PERSIST passes the save from the order to both new items.
  • Hibernate inserts the order first, then the items with the new order_id (17). The addItem helper set item.order, the owning side.
  • Run 2 has no cascade: only the order is inserted. No error, the Java object still says 2 items, but MySQL has none: a silent bug.

cascade lists which operations flow from this entity to the linked ones. PERSIST saves a new parent's new children; MERGE merges a detached parent's children (the Persistence Context module explains merge); REMOVE deletes the children when the parent is deleted; ALL means all of these plus REFRESH and DETACH.

The question to ask is whether the child belongs to this parent alone. An order item does, so Order.items gets CascadeType.ALL, and Hibernate inserts the parent first so the children get its id. A product does not belong to its category, so Product.category gets no cascade, ever: cascading from child to parent is almost always wrong, and REMOVE there would try to delete Mobiles when one phone is deleted.

orphanRemoval = true: removed from the list, deleted from the table

orphanRemoval = true deletes a child row when the child is taken out of its parent's collection, while the parent stays. An orphan is a child removed from the collection; Hibernate deletes its row at the next flush.

order.removeItem(item) should delete the line from the order, with no repository call. Watch the SQL at commit.

Example 2 · orphanRemoval: removeItem deletes the row

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/main/java/com/shoplite/lab/order/CascadeLabService.java/** orphanRemoval: an item taken out of the list is deleted. */@Transactionalpublic void removeFirstItem(int orderId) {    Order order = orders.findById(orderId).orElseThrow();    OrderItem first = order.getItems().get(0);    order.removeItem(first);    System.out.println("Removed item " + first.getId() + "; " + order.getItems().size() + " left");}
// called as removeFirstItem(14)
Output (fresh database)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG SQL - select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? order by i1_0.order_item_id
Removed item 24; 1 left
DEBUG SQL - delete from order_items where order_item_id=?

What this code does

  • Order 14 had items 24 (the Redmi) and 25. removeItem took 24 out of the list and cleared its order link.
  • At commit, orphanRemoval = true turns the orphan into delete from order_items where order_item_id=?. No repository call was needed.
  • Without orphanRemoval, Hibernate would try to set order_id to NULL, which the NOT NULL column refuses.

orphanRemoval differs from cascade REMOVE: REMOVE acts when the parent is deleted, while orphanRemoval acts when a child leaves the collection. Use it only when a child cannot exist without its parent, like order items or a customer's addresses; never for children that could move to another parent.

Two cautions. Replacing the collection (setItems(new ArrayList<>())) breaks orphan tracking, one more reason for helper methods. And orphanRemoval implies remove-on-parent-delete, even without CascadeType.REMOVE.

Order of execution

From removeItem to DELETE

Put the steps in the order they happen when a line is removed from an order.

JPA cascade REMOVE vs ON DELETE CASCADE in MySQL

ON DELETE CASCADE is a foreign key rule inside MySQL: when a parent row is deleted, the database deletes the child rows itself. JPA cascade REMOVE does the same work in Hibernate, loading and deleting the children one by one.

A delete can cascade in two places, in Hibernate or in MySQL. Delete order 14 both ways and count the statements.

Example 3 · Deleting an order: JPA cascade vs the database

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
/** cascade REMOVE: deleting the order deletes its items first. */@Transactionalpublic void deleteOrder(int orderId) {    orders.deleteById(orderId);    System.out.println("Deleted order " + orderId);}
// Run 1: @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)// Run 2: @OneToMany(mappedBy = "order", cascade = {CascadeType.PERSIST, CascadeType.MERGE})//        relies on the schema: order_items.order_id ... REFERENCES orders ON DELETE CASCADE
Output
--- Run 1: JPA cascade REMOVE
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG SQL - select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? order by i1_0.order_item_id
Deleted order 16
DEBUG SQL - delete from order_items where order_item_id=?
DEBUG SQL - delete from order_items where order_item_id=?
DEBUG SQL - delete from orders where order_id=?
--- Run 2: MySQL ON DELETE CASCADE (fresh database)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
Deleted order 16
DEBUG SQL - delete from orders where order_id=?
SELECT COUNT(*) AS items_of_order_16 FROM order_items WHERE order_id = 16;
+-------------------+
| items_of_order_16 |
+-------------------+
|                 0 |
+-------------------+

What this code does

  • Run 1: Hibernate loads the 2 items and deletes them one by one before the order: 1 + 1 SELECTs and 3 DELETEs.
  • Run 2: one delete from orders. MySQL's ON DELETE CASCADE removed both items, as the count shows.
  • For 2 items either is fine. For an order with 2,000 rows, or a bulk cleanup, the database rule is far cheaper.

ShopLite's schema has ON DELETE CASCADE on order_items.order_id and addresses.customer_id, so deleting an order works even without JPA REMOVE: Hibernate sends one DELETE FROM orders and MySQL removes the items. Hibernate's cascade costs one SELECT plus one DELETE per child, but it also runs entity callbacks and keeps loaded objects consistent.

Rules of thumb: keep the database rule as the safety net, use JPA REMOVE or orphanRemoval for small, owned collections, and for bulk deletes (thousands of rows) rely on the database or a bulk query. ShopLite's API never deletes orders, because order history must stay.

TransientPropertyValueException: an unsaved instance

A transient entity is an object created with new that was never saved: it has no id and Hibernate does not know it. A saved entity that links to a transient one, without cascade, fails with TransientPropertyValueException.

A new product is linked to a Category made with new. Hibernate cannot write a foreign key that points at a row that does not exist.

Example 4 · TransientPropertyValueException: linking to a category that was never saved

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
@Transactionalpublic void categoryWithUnsavedParent() {    Category gadgets = new Category("Gadgets", null);                 // transient    categories.save(new Category("Wearables", gadgets));    System.out.println("save() returned");}
/** A new Category that was never saved, and no cascade on Product.category. */@Transactionalpublic void productWithUnsavedCategory() {    Category watches = new Category("Smart Watches", null);          // transient    products.save(new Product("ACC-SW01", "Noise ColorFit Pro 5", watches, new BigDecimal("3499.00"), 25));}
// Run 2 uses Product.category with @JoinColumn(name = "category_id", nullable = false)
Output
--- Run 1: categoryWithUnsavedParent() (parent_id is nullable)
DEBUG SQL - insert into categories (name,parent_id) values (?,?)
save() returned
InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: Persistent instance of 'com.shoplite.lab.category.Category' references an unsaved transient instance of 'com.shoplite.lab.category.Category' (persist the transient instance before flushing) [com.shoplite.lab.category.Category.parent -> com.shoplite.lab.category.Category]
--- Run 2: productWithUnsavedCategory()
WARN  action - HHH90032003: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity.
The unsaved transient entity must be saved in an operation prior to saving these dependent entities.
	Unsaved transient entity: [com.shoplite.lab.category.Category with null id]
	Dependent entities: [[com.shoplite.lab.product.Product with null id]]
	Non-nullable associations: [com.shoplite.lab.product.Product.category]
InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: Instance of 'com.shoplite.lab.product.Product' references an unsaved transient instance of 'com.shoplite.lab.category.Category' (persist the transient instance) [com.shoplite.lab.product.Product.category -> com.shoplite.lab.category.Category]

What this code does

  • Run 1: the Wearables row is inserted with parent_id NULL, planning to fix it later; at flush Hibernate finds the parent was never saved and throws. The insert is rolled back.
  • Run 2: the link is required, so Hibernate warns (HHH90032003) and fails inside save(), before any SQL.
  • The fix is to use an existing category: categories.getReferenceById(4). Adding cascade to Product.category would create categories by accident.

Spring wraps the exception in InvalidDataAccessApiUsageException. In Hibernate 7 the message reads "Persistent instance of '...Category' references an unsaved transient instance of '...Category' (persist the transient instance before flushing)"; older versions said "object references an unsaved transient instance - save the transient instance before flushing". With a required (nullable = false) link, Hibernate also logs warning HHH90032003 and fails at save() itself.

The fix is almost never "add cascade to the child side". Save the parent first, or better, load the existing one: a new product should use categories.findById(id) or getReferenceById(id), never new Category(...). Add cascade only on a parent-to-owned-child link, as on Order.items.

Fix the error

Fix the cascade error

Pick the line that replaces the highlighted one.

Round 1 of 2

A new product points at a category that was never saved.

Product band = new Product("ACC-FB01", "Fitness Band");
band.setCategory(new Category("Wearables", null));
products.save(band);

Error

InvalidDataAccessApiUsageException: TransientPropertyValueException:
Persistent instance of 'Product' references an unsaved transient instance of 'Category'

Cascade REMOVE on @ManyToMany deletes shared rows

CascadeType.ALL passes every operation (PERSIST, MERGE, REMOVE, REFRESH and DETACH) from parent to children. On a @ManyToMany it means deleting a student also deletes their courses, which are shared rows, so it is almost never right there.

Courses are shared: Java Basics belongs to many students. Delete a student whose courses has cascade = ALL and see what happens.

Example 5 · @ManyToMany(cascade = CascadeType.ALL): deleting a student deletes courses

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
@ManyToMany(cascade = CascadeType.ALL)                 // WRONG for many-to-many@JoinTable(name = "student_courses",        joinColumns = @JoinColumn(name = "student_id"),        inverseJoinColumns = @JoinColumn(name = "course_id"))@OrderBy("id")private Set<Course> courses = new LinkedHashSet<>();
@Transactionalpublic void removeStudent(int studentId) {    students.deleteById(studentId);}
// called as removeStudent(2): Ravi Kumar takes Java Basics (shared with Asha) and SQL
Output
DEBUG SQL - select s1_0.student_id,s1_0.full_name from students s1_0 where s1_0.student_id=?
DEBUG SQL - select c1_0.student_id,c1_1.course_id,c1_1.title from student_courses c1_0 join courses c1_1 on c1_1.course_id=c1_0.course_id where c1_0.student_id=? order by c1_0.course_id
DEBUG SQL - delete from student_courses where student_id=?
DEBUG SQL - delete from courses where course_id=?
WARN  error - HHH000247: ErrorCode: 1451, SQLState: 23000
WARN  error - Cannot delete or update a parent row: a foreign key constraint fails (`w_rel`.`student_courses`, CONSTRAINT `fk_sc_course` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`))
DataIntegrityViolationException: could not execute statement [Cannot delete or update a parent row: a foreign key constraint fails (`w_rel`.`student_courses`, CONSTRAINT `fk_sc_course` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`))] [delete from courses where course_id=?]

What this code does

  • Deleting Ravi first removes his link rows, then cascades REMOVE to his courses: delete from courses where course_id=? for Java Basics.
  • Asha still takes Java Basics, so MySQL blocks it (error 1451) and the whole transaction rolls back. Had SQL come first, it would have been deleted with no error.
  • With no cascade, the same deleteById(2) deletes only Ravi's link rows and his student row, which is what the admin meant.

What really happens depends on the data. If a course is still linked to another student, MySQL blocks the delete with a foreign key error, and the whole operation fails. If a course happened to be linked only to this student, it is silently deleted, and the course catalogue loses a row.

For @ManyToMany, use no cascade, or at most PERSIST and MERGE when you create both sides together. Removing the link rows needs no cascade at all: deleting a student already deletes their rows in the link table.

Next step

Check your understanding

12 quick questions