Java Reference
In-Depth Information
The annotation to use to indicate a one-to-one relationship between two JPA
entities is @OneToOne . Our schema doesn't have any one-to-one relationship between
tables, therefore this annotation was not added to any of the entities generated by
the wizard.
One-to-one relationships are not very popular in database schemas,
since all data in a single entity is kept in a single table. Nevertheless JPA
supports one-to-one relationships in case it is needed.
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 type of the JPA entity at the other side of the relationship. 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
since 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.
@Entity
@Table(name="BELLY_BUTTON")
public class BellyButton implements Serializable(
 
Search WWH ::




Custom Search