Menu

One-to-One Mapping

One-to-One Mapping

Owning and Inverse Sides

In a one-to-one relationship, one row is linked to exactly one row in another table. The side with the foreign key column is the owning side and uses @JoinColumn.

For a bidirectional relationship, the other side uses mappedBy to point to the owning field. This tells Hibernate not to create a second foreign key.

@Entity
public class Student {
    @Id @GeneratedValue
    private Long id;

    @OneToOne
    @JoinColumn(name = "id_card_id")
    private IdCard idCard;
}

@Entity
public class IdCard {
    @Id @GeneratedValue
    private Long id;
    private String number;

    @OneToOne(mappedBy = "idCard")
    private Student student;
}

Code Explanation:

  • Student owns the relationship, so the students table gets an id_card_id foreign key.
  • mappedBy = "idCard" in IdCard refers to the field name in Student.
  • Changes to the relationship are saved only through the owning side.
  • The inverse side cannot be loaded lazily in the usual way, because Hibernate must query to know whether a value exists.

An alternative is a shared primary key using @MapsId, where the child uses the parent's key as its own. It avoids the extra column and suits strict one-to-one data.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details