Cascading in Hibernate propagates an operation performed on a parent entity to its associated child entities automatically. Instead of manually saving, updating, or deleting each related object, you configure a cascade rule once on the association and Hibernate applies it whenever the parent changes.
Key Points: • CascadeType.PERSIST, MERGE, REMOVE, REFRESH, and DETACH each control propagation of a specific operation. • CascadeType.ALL applies every cascade type, which is convenient but can be dangerous on shared associations. • Cascading is declared on the association annotation, typically @OneToMany or @OneToOne, via the cascade attribute. • It reduces boilerplate code for managing the lifecycle of tightly-owned child objects (e.g. an Order and its OrderItems). • Cascading is independent of orphanRemoval, which specifically deletes children removed from the collection.
Example: If an Order entity has a @OneToMany(cascade = CascadeType.ALL) collection of OrderItem, calling session.save(order) automatically saves all the OrderItem objects in that collection without an explicit save() call for each one.
Code Example:
@Entity
public class Order {
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
}Interview Tip: A concise interview answer is:
"Cascading lets an operation on a parent entity automatically propagate to its associated children, configured through CascadeType values like PERSIST, MERGE, or REMOVE on the association mapping — so saving or deleting an Order can automatically save or delete its OrderItems without extra code."