Java Reference
In-Depth Information
Listing 6-16.
Mapping a Many-to-One Relationship from the
Publisher
Entity to the
Book
Entity
@ManyToOne
@JoinColumn(name = "publisher_id")
public Publisher getPublisher() {
return publisher;
}
The
@ManyToOne
annotation takes a similar set of attributes to
@OneToMany
. The following
list describes the attributes, all of which are optional.
cascade
indicates the appropriate cascade policy for operations on the association;
it defaults to none.
fetch
indicates the fetch strategy to use; it defaults to
LAZY
.
optional
indicates whether the value can be null; it defaults to
true
.
targetEntity
indicates the entity that stores the primary key—this is normally inferred
from the type of the field or property (
Publisher
in the preceding example).
We have also supplied the optional
@JoinColumn
attribute to name the foreign key column
required by the association something other than the default (
publisher
)—this is not neces-
sary, but it illustrates the use of the annotation.
When a unidirectional one-to-many association is to be formed, it is possible to express
the relationship using a link table. This is achieved by adding the
@JoinTable
annotation as
shown in Listing 6-17.
2
Listing 6-17.
A Simple Unidirectional One-to-Many Association with a Join Table
@OneToMany(cascade = ALL)
@JoinTable
public Set<Book> getBooks() {
return books;
}
The
@JoinTable
annotation provides attributes that allow various aspects of the link table
to be controlled. These attributes are as follows:
name
is the name of the join table to be used to represent the association.
catalog
is the name of the catalog containing the join table.
schema
is the name of the schema containing the join table.
joinColumns
is an array of
@JoinColumn
attributes representing the primary key of the
entity at the “one” end of the association.
inverseJoinColumns
is an array of
@JoinColumn
attributes representing the primary key of
the entity at the “many” end of the association.
2. When a join table is being used, the foreign key relationship is maintained within the join table
itself—it is therefore not appropriate to combine the
mappedBy
attribute of the
@OneToMany
annotation
with the use of an
@JoinTable
annotation.
Search WWH ::
Custom Search