Java Reference
In-Depth Information
private String orderNumber;
@Column(name = "ORDER_DESCRIPTION")
private String orderDescription;
@JoinTable(name = "ORDER_ITEM", joinColumns =
{@JoinColumn(name = "CUSTOMER_ORDER_ID",
referencedColumnName =
"CUSTOMER_ORDER_ID")},
inverseJoinColumns = {@JoinColumn(name = "ITEM_ID",
referencedColumnName = "ITEM_ID")})
@ManyToMany
private Collection<Item> itemIdCollection;
@JoinColumn(name = "CUSTOMER_ID",
referencedColumnName = "CUSTOMER_ID")
@ManyToOne
private Customer customerId;
//Constructor, getters, setters and other methods deleted for
//brevity
}
Notice that the
CustomerOrder
entity has a property of type
java.util.Collection
named
itemIdCollection
.
Again, the property name generated by the wizard could be improved. A
better name would have been
itemCollection
.
This property holds all items for the order. Notice that the field is decorated with
the
@ManyToMany
annotation. This annotation is used to declare a many-to-many
relationship between the
CustomerOrder
and
Item
JPA entities. Notice that the field
is also annotated with the
@JoinTable
annotation. This annotation is necessary since
a join table is necessary in a database schema whenever there is a many-to-many
relationship between tables. Using a join table allows us to keep the data in the
database normalized.
The
@JoinTable
annotation allows us to specify the table in the schema that is
used to denote the many-to-many relationship in the schema. The value of the
name
attribute of
@JoinTable
must match the name of the join table in the schema.
The value of the
joinColumns
attribute of
@JoinColumn
must be the foreign key
relationship between the join table and the owning side of the relationship. We
already looked at the
@JoinColumn
annotation when looking at one-to-many
relationships. In this case, its
name
attribute must match the name of the column in
the join table that has the foreign key relationship, and its
referencedColumnName