concept bids in category hibernate

appears as: bids
Java Persistence with Hibernate, Second Edition

This is an excerpt from Manning's book Java Persistence with Hibernate, Second Edition.

This association between the two classes allows bidirectional navigation: the many-to-one is from this perspective a one-to-many multiplicity (again, one item can have many bids). The scaffolding code for the bids property uses a collection interface type, java.util.Set. JPA requires interfaces for collection-typed properties, where you must use java.util.Set, java.util.List, or java.util.Collection rather than HashSet, for example. It’s good practice to program to collection interfaces anyway, rather than concrete implementations, so this restriction shouldn’t bother you.

The default for the fetch parameter of a collection mapping is always FetchType.LAZY. You won’t need this option in the future. It’s a good default setting; the opposite would be the rarely needed EAGER. You don’t want all the bids eagerly loaded every time you load an Item. They should be loaded when accessed, on demand.

At commit time, Hibernate examines the managed/persistent Item instance and looks into the bids collection. It then calls persist() internally on each of the referenced Bid instances, saving them as well. The value stored in the column BID#ITEM_ID is taken from each Bid by inspecting the Bid#item property. The foreign key column is “mapped by” with @ManyToOne on that property.

Listing 7.19. Cascading removal from Item to all bids

Path: /model/src/main/java/org/jpwh/model/associations/onetomany/cascaderemove/Item.java

@Entity
public class Item {
<enter/>
    @OneToMany(mappedBy = "item",
               cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    protected Set<Bid> bids = new HashSet<>();
<enter/>
    // ...
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":7}],[{\"line\":3,\"ch\":4},{\"line\":3,\"ch\":14}]]"}
!@%STYLE%@!

Just as before with PERSIST, Hibernate now cascades the remove() operation on this association. If you call EntityManager#remove() on an Item, Hibernate loads the bids collection elements and internally calls remove() on each instance: