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, all data in a single entity is typically kept in a single
table, since 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 have 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