3.8.7.7. One-Sided One-Many Mapping
The previous section covered the use of ElementJoinColumn annotations in conjunction with a ContainerTable for mapping collections to dedicate tables. ElementJoinColumn s, however, have one additional use: to create a one-sided one-many mapping.
Standard JPA supports OneToMany fields without a mappedBy inverse, but only by mapping these fields to a JoinTable (see Join Table in the JPA Overview for details). Often, you’d like to create a one-many association based on an inverse foreign key (logical or actual) in the table of the related type.
Consider the model above. Subscription has a collection of LineItem s, but LineItem has no inverse relation to Subscription.
To retrieve all of the LineItem records for a Subscription, we join the SUB_ID inverse foreign key column in the LINE_ITEM table to the primary key column of the SUB table.
The example below shows how to represent this model in mapping annotations.
Note that OpenJPA automatically assumes an inverse foreign key mapping when element join columns are given, but no container or join table is given.
package org.mag.subscribe;
import org.apache.openjpa.persistence.jdbc.*;
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public class LineItem {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
@Id private long id;
@OneToMany
@ElementJoinColumn(name="SUB_ID", referencedColumnName="ID")
private Collection<LineItem> items;
...
}