Java Reference
In-Depth Information
Define a
@OneToMany
relationship to the
Section
entity. Set the
cascade
element
to
CascadeType.ALL
to cascade all operations to the target of the association. The
mappedBy
element specifies the field that owns the relationship. In a one-to-many
relationship the many-side must be the owning side of the relationship, which in
the example is the
Edition
entity. The
fetch
element specifies the fetch strategy.
The default strategy is
LAZY
, which does not fetch the associated entities when an
entity is retrieved.
LAZY
fetching is useful if an entity has a number of associations,
which further have associations and all that is required is a particular entity. But, as
we require the associated entities too, set fetch strategy to
EAGER
, which fetches all
the associated entities. Specify a join table for the one-to-many mapping using the
@
JoinTable
annotation. The
name
element of the
@JoinTable
specifies the table name.
The
name
element is optional and defaults to the concatenated names of the two
associated primary entity tables The
joinColumns
element specifies the foreign key
columns of the join table that are mapped to the primary table of the owning entity,
and the
inverseJoinColumns
element specifies the foreign key columns of the
join table that reference the table for the non-owning entity. The
joinColumns
and
inverseJoinColumns
are also optional and default values are used if not specified.
The one-to-many mapping for the edition-section relationship is as follows:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "edition",fetch =
FetchType.EAGER)
@JoinTable(name = "Edition_Section", joinColumns = {
@JoinColumn(name = "edition_section_id",
referencedColumnName = "id")} ,
inverseJoinColumns = {
@JoinColumn(name = "section_id",
referencedColumnName ="id")} )
Specify the getter/setter methods for the
Section
entity:
public List<Section> getSections() {
return sections;
}
public void setSections(List<Section> sections) {
this.sections = sections;
}
Also add methods to add and remove a
Section
entity:
public void addSection(Section section) {
this.getSections().add(section);
section.setEdition(this);
}
public void removeSection(Section section) {
this.getSections().remove(section);
}
Search WWH ::
Custom Search