Java Reference
In-Depth Information
Mapping an Embedded (Component) One-to-One Association
When all the fields of one entity are maintained within the same table as another, the
enclosed entity is referred to in Hibernate as a
component
. The EJB 3 standard refers to
such an entity as being
embedded
.
The
@Embedded
and
@Embeddable
attributes are used to manage this relationship. In this
book's database example, we associate an
AuthorAddress
class with an
Author
class in this way.
The
AuthorAddress
class is marked with the
@Embeddable
annotation. An embeddable
entity must be composed entirely of basic fields and attributes. An embeddable entity can
only use the
@Basic
,
@Column
,
@Lob
,
@Temporal
, and
@Enumerated
annotations. It cannot main-
tain its own primary key with the
Id
tag because its primary key is the primary key of the
enclosing entity.
The
@Embeddable
annotation itself is purely a marker annotation, and takes no additional
attributes, as demonstrated in Listing 6-11. Typically, the fields and properties of the embedd-
able entity need no further markup.
Listing 6-11.
Marking an Entity for Embedding Within Other Entities
@Embeddable
public class AuthorAddress {
...
}
The enclosing entity then marks appropriate fields or getters in entities, making use of the
embeddable class with the
@Embedded
annotation, as shown in Listing 6-12.
Listing 6-12.
Marking an Embedded Property
@Embedded
public AuthorAddress getAddress() {
return this.address;
}
The
@Embedded
annotation draws its column information from the embedded type, but
permits the overriding of a specific column or columns with the
@AttributeOverride
and
@AttributeOverrides
tags (the latter to enclose an array of the former if multiple columns are
being overridden). For example, Listing 6-13 shows how to override the default column names
of the
address
and
country
attributes of
AuthorAddress
with columns named
ADDR
and
NATION
.
Listing 6-13.
Overriding Default Attributes of an Embedded Property
@Embedded
@AttributeOverrides({
@AttributeOverride(name="address",column=@Column(name="ADDR")),
@AttributeOverride(name="country",column=@Column(name="NATION"))
})
public AuthorAddress getAddress() {
return this.address;
}
Search WWH ::
Custom Search