Java Reference
In-Depth Information
The procedure to indicate a one-to-one relationship between two entities is similar
to what we have already seen. The owning side of the relationship must have a field
of the JPA entity type on the other side of the relationship, and this field must be
decorated with the
@OneToOne
and
@JoinColumn
annotations.
Suppose we had a schema in which a one-to-one relationship was defined between
two tables named
PERSON
and
BELLY_BUTTON
. This is a one-to-one relationship
because each person has one belly button and each belly button belongs to only one
person (the reason the schema was modeled this way instead of having the columns
relating to the
BELLY_BUTTON
table in the
PERSON
table escapes me, but bear with
me—I'm having a hard time coming up with a good example!).
@Entity
public class Person implements Serializable {
@JoinColumn(name="BELLY_BUTTON_ID")
@OneToOne
private BellyButton bellyButton;
public BellyButton getBellyButton(){
return bellyButton;
}
public void setBellyButton(BellyButton bellyButton){
this.bellyButton = bellyButton;
}
}
If the one-to-one relationship is unidirectional (we can only get the belly button from
the person), this would be all we had to do. If the relationship is bidirectional, then
we need to add the
@OneToOne
annotation on the other side of the relationship and
use its
mappedBy
attribute to indicate the other side of the relationship. The code is
as follows:
@Entity
@Table(name="BELLY_BUTTON")
public class BellyButton implements Serializable(
{
@OneToOne(mappedBy="bellyButton")
private Person person;
public Person getPerson(){
return person;
}
public void getPerson(Person person){
this.person=person;
}
}