Transitive persistence makes a persistence operation on one entity propagate to associated entities. Without it, new associated entities have independent lifecycles: saving an Item does not, by itself, save its new Bids. Each Bid must be saved separately. Cascading reduces those calls, but the entities still need to be linked correctly in memory. section 8.3.3
Place CascadeType.PERSIST on Item.bids to make new Bids persistent when their Item is persisted. section 8.3.3
Save an Item and its Bids
Create the Item and Bids, set each Bid.item, and add each Bid to Item.bids. With CascadeType.PERSIST on the collection, one itemRepository.save(item) replaces separate saves for the Bids. At commit, Hibernate examines the managed Item’s collection; the BID.ITEM_ID foreign-key value comes from each Bid.item property. section 8.3.3
Choose cascades to match the relationship’s lifecycle:
- CascadeType.REMOVE propagates deletion from an Item to its Bids. By contrast, orphanRemoval = true deletes a Bid removed from the Item’s collection. Neither operation cleans up references held elsewhere in memory automatically. section 8.3.3
- A bidirectional one-to-one association can cascade persistence from a User to its shipping Address; the shown shared-primary-key mapping also uses a Hibernate-specific identifier generator. section 9.1.2
- A Category can cascade persistence to new Items in a many-to-many association. Saving the Categories can then persist the linked network, but REMOVE, ALL and orphan deletion are not appropriate when related entities can be shared. section 9.3.1
Cascade deliberately: it can simplify code while having a serious performance consequence. Cascading from a Bid to its Item is usually a poor fit when the Item must already exist; do not treat every association as a shared lifecycle. section 8.3.3
