4.5. One-to-Many

The @javax.persistence.OneToMany annotation defines a many-valued association with one-to-many multiplicity. In Naked Objects' terms this is a collection (or any of its subtypes). As discussed in Section 2.7, “No support for Maps”, Naked Objects does not support java.util.Maps.

It's very common for collections relationships to be bidirectional, with that the referenced "child" entity having a corresponding back reference to its owning parent entity using @ManyToOne. In this case the foreign key that the @ManyToOne requires can also be used to navigate from the parent to the child. We indicate this bidirectionality using the mappedBy attribute. In the parent we have:

@Entity
@DiscriminatorValue("ORD")
public class Order {

    private List<OrderItem> items = new ArrayList<OrderItem>;
    @OneToMany(mappedBy="order")
    public List<OrderItem> getItems() { ... }
    private void setItems(List<OrderItem> items) { ... }

    ...
}

and in the child we have:

@Entity
@DiscriminatorValue("ORI")
public class OrderItem {

    private Order order;
    @ManyToOne
    public Order getOrder() { ... }
    public void setOrder(Order order) { ... }

    ...
}

If the collection is defined using generics to specify the element type (as above), the associated entity type need not be specified; otherwise the entity class must be specified.

The above code isn't complete by the way; for bidirectional relationships you'll need to write code to keep the links in sync. The mutual registration pattern for this; see for example Dan's DDD book for more details if you aren't familiar with it.

On occasion you may have a requirement only for the one-to-many collection in the parent, and no back reference from the child back. From an annotations perspective just omit the mappedBy attribute. However, it's worth being aware that the database schema will be quite different. Because there is no foreign key in the child table to use, Hibernate will create a link table consisting of the (parent_id, child_id) tuples. Retrieving the children of a collection means Hibernate will need to this query this link table and join across to the child entity table.