A JPA association does not make the lifecycles of its entities dependent. A new Item and its new Bids normally require separate save operations, even when each Bid refers to the Item. The association’s cascade option selects which state transitions should propagate from one entity to its associated entities. section 8.3.3 section 13.1
Persist an item and its bids
Map the collection with `@OneToMany(mappedBy = "item", cascade = CascadeType.PERSIST)`. Add each new Bid to the Item’s collection, then call `itemRepository.save(item)` rather than saving every Bid separately. At commit time, Spring Data JPA using Hibernate examines the managed Item and makes its referenced Bids persistent. The `BID.ITEM_ID` foreign-key value comes from each Bid’s `item` property; `mappedBy` identifies that side of the association. section 8.3.3
Choose the direction to match the dependency. Cascading from an Item to its Bids can be useful; cascading a Bid’s save to its Item is usually inappropriate when the Item must already exist. A bidirectional collection also provides navigational access, but adds mapping and Java-code complexity. If a dependent object does not need a shared entity identity, consider an embeddable value type instead. section 8.3.2 section 8.3.3
Select operations deliberately rather than treating every association change alike:
- `PERSIST` propagates persistence; `REMOVE` propagates deletion. With both on the Item collection, deleting an Item can remove its Bids without deleting them individually. section 8.3.3
- `orphanRemoval = true` addresses a different action: removing a Bid from the Item’s collection. A demonstrated save leaves one fewer Bid in the database, but another already-loaded collection can still hold its old in-memory reference. section 8.3.3
- `DETACH`, `MERGE`, and `REFRESH` propagate their corresponding EntityManager operations. Hibernate also identifies `REPLICATE` with `Session#replicate()`. section 13.1.1
Table 13.1 Cascading options for entity association mappings (view table figure)
Compare the cascade options with the EntityManager or Session operations whose state transitions they propagate. section 13.1.1
Do not confuse entity-operation cascades with database-level deletion. Hibernate’s `@OnDelete` can generate a foreign key with `ON DELETE CASCADE`; its cited use affects schema generation. Use transitive deletion carefully, especially when deciding whether associated entities should survive their owner. section 8.3.3
