Java Reference
In-Depth Information
Notice that the
CustomerOrder
entity has a property of type
java.util.Collection
named
itemCollection
. This property holds all items for the order. 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. 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 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 discussed the
@JoinColumn
annotation when discussing 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
attribute must indicate
the name of the primary key column on the owning side of the relationship. The
value of the
inverseJoinColumns
attribute of
@JoinTable
has a similar role as its
joinColumns
attribute, except it indicates the corresponding columns for the non-
owning side of the relationship.
The side of the many-to-many relationship that contains the above annotations is
said to be the owning side of the relationship. Let's look at how the many-to-many
relationship is defined in the non-owning side of the relationship, which in our
case is the
Item
JPA entity. The code is as follows:
package com.ensode.jpa;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "ITEM")
@NamedQueries({
@NamedQuery(name = "Item.findAll", query = "SELECT i FROM Item
i"),