Video in progress
What CascadeType values are there and what does each one mean?
Cascade means passing an operation on the parent entity down to the related entities. The types are PERSIST, MERGE, REMOVE, REFRESH, DETACH, and ALL, which combines them all.
📖 Answer
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
With this, em.persist(order) saves all the new items too, and em.remove(order) deletes them as well.
What each one means, briefly:
PERSIST: when the parent is saved, new children are saved too;MERGE: when a detached parent is merged, the children are merged too;REMOVE: when the parent is deleted, the children are deleted too;REFRESH: when the parent is re-read from the database, so are the children;DETACH: when the parent is detached from the context, so are the children.
The rule: use cascade only for a true "owner and part" relationship, meaning the child has no meaning without the parent. Order → OrderItem: yes. OrderItem → Product: no, because deleting an item must not remove the product from the catalog.
Cascade is normally written on the parent side (@OneToMany). Putting cascade on a @ManyToOne is almost always a mistake.
One more point: cascade works at the JPA level. ON DELETE CASCADE in the database is a different thing, and Hibernate doesn't know about it.
Sign up to mark studied questions and save your progress.