Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Associations and Inheritance

Cascade and Orphan Removal

Understand Hibernate cascading: PERSIST, MERGE, REMOVE, ALL, orphanRemoval, when to cascade from a parent to its children, and when cascading is dangerous.

Once entities are connected, a question appears: when you save an order, must you also save each order line by hand? Cascading says no. It tells Hibernate to pass an operation from a parent entity to its associated children automatically. Used well, it keeps code short; used carelessly, it deletes data you wanted to keep.

Real Hibernate code is read-only here; the runnable programs are plain-Java stand-ins.

Without cascade

Java
Order order = new Order();
OrderLine line = new OrderLine("Pencil", 3);
order.addLine(line);

session.persist(order);      // line is NOT saved
// at flush: TransientObjectException, the order references an unsaved OrderLine

You would have to call session.persist(line) yourself. With a cascade the persist travels along the association:

Java
@Entity
@Table(name = "orders")
public class Order {
    @Id @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    public void addLine(OrderLine line) {
        lines.add(line);
        line.setOrder(this);
    }
}

The cascade types

Type Passes this operation to the children
PERSIST persist (saving a new parent saves new children)
MERGE merge (copying a detached graph into the session)
REMOVE remove (deleting the parent deletes the children)
REFRESH refresh (re-reading from the database)
DETACH detach (taking the graph out of the session)
ALL all of the above

Hibernate also has its own @Cascade annotation for SAVE_UPDATE and similar legacy operations; with the JPA API you do not need it.

orphanRemoval

orphanRemoval = true means: a child that is removed from the parent's collection is deleted from the database.

Java
order.getLines().remove(line);     // at flush: DELETE FROM order_line WHERE id = ?

REMOVE cascades when the parent is deleted. orphanRemoval also reacts when a child is merely disconnected. Both together express "the lines belong to the order and cannot exist without it", which is called a composition.

Two pitfalls:

  • Do not replace the collection (order.setLines(newList)); Hibernate loses track of the old one and throws an error. Clear it and add instead (getLines().clear(); getLines().addAll(newLines)).
  • orphanRemoval is meant for private children. If another entity also references the child, deleting it from one parent breaks the other.

When cascade is right and wrong

Cascade from parent to child Verdict
Order to its lines Yes: lines are owned
Post to its comments Usually yes
Book to its author No: the author is independent and shared
Student to courses (many-to-many) No: never REMOVE/ALL (many-to-many)

The rule: cascade from a parent that owns its children to those children. Never cascade REMOVE toward an entity that other rows reference.

Also remember: CascadeType.ALL on a @ManyToOne is almost always a bug, because deleting a child would try to delete its parent.

Stand-in: a cascading persist

Java Stand-in: cascade PERSIST and REMOVE

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: orphan removal at flush

Java Stand-in: orphanRemoval detects removed children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you persist a parent that references an unsaved child without a cascade?

    Hibernate cannot write a foreign key to an unsaved entity.
  2. 2. What does orphanRemoval = true do?

    Children disconnected from the parent are deleted at flush.
  3. 3. Where is CascadeType.REMOVE dangerous?

    Removing a book would delete an author that other books still reference.
  4. 4. What should you do instead of order.setLines(newList) when orphanRemoval is on?

    Replacing the collection breaks Hibernate's tracking of the original managed collection.

Summary

  • Cascading passes persist, merge, remove and more from a parent to its associations.
  • orphanRemoval also deletes children removed from the collection.
  • Cascade from an owner to its private children (composition); never toward shared entities.
  • Modify managed collections in place instead of replacing them.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Inheritance Mapping Strategies