A bidirectional relationship lets code navigate an association from either participating object. In an auction domain, each Bid refers to one Item, while an Item holds a collection of its Bids. The two properties express the same relationship from many-to-one and one-to-many perspectives. section 3.2.4
Both in-memory links must agree. Adding a Bid to an Item’s collection without setting Bid.item leaves the objects inconsistent; setting only Bid.item has the opposite problem. Put both changes in one operation, such as Item.addBid(bid), and reject a null bid or one already assigned to an Item. An unmodifiable collection getter prevents callers from bypassing that operation. section 3.2.4
Listing 3.3 A convenience method simplifies relationship management
Path: Ch03/domainmodel/src/main/java/com/manning/javapersistence/ch03/ex03 /Item.java public void addBid(Bid bid) { if (bid == null) throw new NullPointerException("Can't add null Bid"); if (bid.getItem() != null) throw new IllegalStateException( "Bid is already assigned to an Item"); bids.add(bid); bid.setItem(this); }
The addBid method checks the proposed link, adds the Bid to the collection, and sets its Item reference. section 3.2.4
For a JPA entity association, map Bid.item with @ManyToOne and Item.bids with @OneToMany(mappedBy = "item"). The Bid-side mapping handles the ITEM_ID foreign key; mappedBy tells Hibernate to load the collection through that already-mapped property. A collection is lazy-loaded by default, so loading an Item need not immediately load all its Bids. section 8.3.2
Listing 8.17 Item has a collection of Bid references
Path: Ch08/mapping-associations/src/main/java/com/manning/javapersistence /ch08/onetomany/bidirectional/Item.java @Entity public class Item { // . . . @OneToMany(mappedBy = "item", #1 fetch = FetchType.LAZY) #2 private Set<Bid> bids = new HashSet<>(); // . . . } #1 The <kbd>@OneToMany</kbd> annotation is required to make the association bidirectional. In this case, we also have to set the <kbd>mappedBy</kbd> parameter. #2 The argument is the name of the property on the “other side.” The fetching will be <kbd>LAZY</kbd> by default.
The Item mapping shows how mappedBy names the Bid property and how the collection is declared. section 8.3.2
Map the reverse collection when the application regularly navigates from an Item to its Bids or needs collection-based cascading. If it usually needs subsets or varying orders, queries may be more useful than maintaining a collection. Bidirectional navigation can also introduce shared references that affect whether a domain object needs entity identity rather than value-type treatment. section 8.3.2 section 5.1.3
