Transitive persistence propagates a persist operation from an entity to associated entities through a configured cascade. Without it, associated entities have independent lifecycles and new instances must be persisted separately. section 8.3.3
For an Item with new Bid entities, configure CascadeType.PERSIST on Item.bids. Set Bid.item and add each bid to Item.bids to keep both sides consistent, then save the item instead of saving every bid separately. section 8.3.3
The Item mapping enables persistence to cascade to its bids. section 8.3.3
Listing 8.22 All referenced bids are automatically made persistent
Path: Ch08/mapping-associations/src/test/java/com/manning/javapersistence /ch08/onetomany/cascadepersist/MappingAssociationsSpringDataJPATest.java Item item = new Item("Foo"); Bid bid = new Bid(BigDecimal.valueOf(100), item); Bid bid2 = new Bid(BigDecimal.valueOf(200), item); item.addBid(bid); item.addBid(bid2); itemRepository.save(item); #1 #1 We save the bids automatically, but later. At commit time, Spring Data JPA using Hibernate examines the managed/persistent <kbd>Item</kbd> instance and looks into the bids collection. It then calls <kbd>save()</kbd> internally on each of the referenced <kbd>Bid</kbd> instances, saving them as well. The value stored in the column <kbd>BID#ITEM_ID</kbd> is taken from each <kbd>Bid</kbd> by inspecting the <kbd>Bid#item</kbd> property. The foreign key column is <kbd>mappedBy</kbd> with <kbd>@ManyToOne</kbd> on that property.
Saving the item makes its referenced bids persistent. In this example, Spring Data JPA with Hibernate examines the managed item and its collection at commit time; Bid.item supplies the foreign key value. section 8.3.3
Choose the cascade direction to match the dependency. Cascading from a bid to its item is usually inappropriate: the item must exist for the bid to be valid. Cascading reduces management code but can have serious performance consequences. section 8.3.3
Related lifecycle operations require separate decisions:
- CascadeType.REMOVE propagates removal from an item to its bids; orphanRemoval instead handles a bid removed from the collection. section 8.3.3
- Database removal does not automatically clean up every in-memory reference. Keep other associations consistent when removing an entity. section 8.3.3
- For many-to-many associations, CascadeType.PERSIST can save new associated items, but ALL, REMOVE and orphan deletion are inappropriate when related entities may be shared. section 9.3.1
Shared primary key
In a bidirectional one-to-one association, persisting a User cascades to its shipping Address. A Hibernate foreign identifier generator takes the referenced User identifier as the Address primary key, simplifying persistence order. section 9.1.2
