Cascade Operations

Basic Java
≈ 1 min read

Cascade propagates an operation to related Entities

Sometimes related objects form one lifecycle unit. For example, when a new order is saved, the line items created together with it may need to be saved as well. JPA lets you explicitly specify which operations should propagate across a relationship.

@OneToMany(mappedBy = "order", cascade = CascadeType.PERSIST)
private List<OrderItem> items = new ArrayList<>();

Now persist(order) can propagate the PERSIST operation to the elements of the items collection. Without cascade, related objects do not automatically participate in the same lifecycle operation just because a reference points to them.

Cascades are chosen according to relationship semantics

  • PERSIST — propagate persistence;
  • MERGE — propagate merge;
  • REMOVE — propagate removal;
  • REFRESH and DETACH — propagate the corresponding lifecycle operations;
  • ALL — include all of the operations listed above.
Do not add CascadeType.ALL automatically. Be especially careful with REMOVE: deleting one object should not always delete a related object that may be used elsewhere.