A cascade operation propagates a selected entity lifecycle operation across a JPA association. Cascading is not enabled by default: associated entities otherwise have independent lifecycles, even when they reference each other. section 13.1
Persist an item and its bids
For an Item with a one-to-many collection of Bid entities, set cascade = CascadeType.PERSIST on the collection. Create the item and bids, link them, and save the item; the referenced bids become persistent without separate repository saves. In this bidirectional mapping, Bid.item supplies the foreign-key value. section 8.3.3
The mapping enables persist cascading from Item to its bids and identifies Bid.item as the other side of the association. section 8.3.3
Choose cascade options according to the operations that should propagate:
- PERSIST makes associated entities persistent; REMOVE removes them when the parent is removed. These operations take effect at flush time. section 13.1.1
- DETACH detaches associated entities from the persistence context; MERGE merges associated transient or detached entities. section 13.1.1
- REFRESH propagates refresh; Hibernate also provides a REPLICATE cascade for Session.replicate(). section 13.1.1
Use removal cascading carefully. For example, adding CascadeType.REMOVE to Item.bids allows deleting an item to remove its bids. A many-to-one cascade in the opposite direction is often inappropriate: a bid normally refers to an item that already exists. section 8.3.3
Orphan removal is a separate mapping switch: with orphanRemoval = true, removing a bid from the collection can remove it from the database. Other in-memory references to that bid are not automatically cleaned up. Database-level ON DELETE CASCADE is another mechanism; Hibernate’s @OnDelete affects schema generation. section 8.3.3
A collection mapping also provides navigational access, but adds code and complexity. Cascade is optional; it should express a real lifecycle dependency rather than alone justify mapping the collection. section 8.3.2
