background image

Self-Referential Relationships

<< Persistence in the EJB Tier | One-to-Many Relationship >>
<< Persistence in the EJB Tier | One-to-Many Relationship >>

Self-Referential Relationships

Self-Referential Relationships
A self-referential relationship is a relationship between relationship fields in the same entity.
Part
has a field bomPart that has a one-to-many relationship with the field parts, which is also
in Part. That is, a part can be made up of many parts, and each of those parts has exactly one
bill-of-material part.
The primary key for Part is a compound primary key, a combination of the partNumber and
revision
fields. It is mapped to the PARTNUMBER and REVISION columns in the EJB_ORDER_PART
table.
...
@ManyToOne
@JoinColumns({
@JoinColumn(name=
"BOMPARTNUMBER",
referencedColumnName=
"PARTNUMBER"),
@JoinColumn(name=
"BOMREVISION",
referencedColumnName=
"REVISION")
})
public Part getBomPart() {
return bomPart;
}
...
@OneToMany(mappedBy=
"bomPart")
public Collection<Part> getParts() {
return parts;
}
...
One-to-One Relationships
Part
has a field, vendorPart, that has a one-to-one relationship with VendorPart's part field.
That is, each part has exactly one vendor part, and vice versa.
Here is the relationship mapping in Part:
@OneToOne(mappedBy=
"part")
public VendorPart getVendorPart() {
return vendorPart;
}
Here is the relationship mapping in VendorPart:
@OneToOne
@JoinColumns({
@JoinColumn(name=
"PARTNUMBER",
referencedColumnName=
"PARTNUMBER"),
@JoinColumn(name=
"PARTREVISION",
The order Application
The Java EE 5 Tutorial · September 2007
712