Java Reference
In-Depth Information
Neither Hibernate nor the EJB 3 standard supports mapping an embedded object across
more than one table. In practice, if you want this sort of persistence for your embedded entity,
you will usually be better off making it a first-class entity (i.e., not embedded) with its own
@Entity marker and @Id annotations, and then mapping it via a conventional one-to-one
association, as explained in the next section.
Mapping a Conventional One-to-One Association
There is nothing intrinsically wrong with mapping a one-to-one association between two enti-
ties where one is not a component of (i.e., embedded into) the other. The relationship is often
somewhat suspect, however. You should give some thought to using the embedded technique
described previously before using the @OneToOne annotation.
Assuming that you are resolute on declaring the association in this way (perhaps because
you anticipate converting it to a one-to-many or many-to-one relationship in the foreseeable
future), applying the annotation is quite simple—all of the attributes are optional. Listing 6-14
shows how simply a relationship like this might be declared.
Listing 6-14. Declaring a Simple One-to-One Relationship
@OneToOne
public Address getAddress() {
return this.address;
}
The @OneToOne annotation permits the following optional attributes to be specified:
targetEntity can be set to the class of an entity storing the association. If left unset, the
appropriate type will be inferred from the field type, or the return type of the property's
getter.
cascade can be set to any of the members of the javax.persistence.CascadeType enumer-
ation. It defaults to none being set. See the “Cascading Operations” sidebar for a
discussion of these values.
fetch can be set to the EAGER or LAZY members of FetchType .
optional indicates whether the value being mapped can be null.
mappedBy indicates that a bidirectional one-to-one relationship is owned by the named
entity. 1 The owning entity contains the primary key of the subordinate entity.
Mapping a Many-to-One or One-to-Many Association
A many-to-one association and a one-to-many association are the same association seen from
the perspective of the owning and subordinate entities, respectively.
1. An association is bidirectional if each entity maintains a property or field representing its end of the
same relationship. For example, if our Address class maintained a reference to the Publisher located
there, and the Publisher class maintained a reference to its Address , then the association would be
bidirectional.
Search WWH ::




Custom Search