Cascade Operations
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;REFRESHandDETACH— 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.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in