Hibernate – @OneToOne Annotation
Last Updated :
21 Jun, 2023
@OnetoOne annotation in Hibernate is used to create a one-to-one association between two entities. The one-to-one annotation indicates that one instance of an entity is associated with only one instance of the other entity. When we annotate a field or method with @Onetoone annotation then Hibernate will create the one-to-one relation between these two entities. We can use @OnetoOne annotation on either side of the association depending on the directionality of the relationship.
Examples for @OneToOne Annotation
Example 1:
Java
@Entity
public class Student {
@Id @GeneratedValue private long id;
private String name;
@OneToOne (mappedBy = "student" )
private Education education;
}
@Entity
public class Education {
@Id
@GeneratedValue
private long id;
private int sscPercentage;
private int hscPercentage;
@OneToOne
@JoinColumn (name = "id" )
private Student student;
}
|
Code Explanation:
In the above example, the Student entity is having a one-to-one relationship with the Education entity. The student entity has the fields as student name, id, and student education. The student entity is the owner of this relationship as it is indicated by the mappedBy attribute in the @OnetoOne association on the education field.
The Education entity is not the owner of this relationship. It uses @JoinColumn annotation to specify the foreign key column name id that references the primary key of the Student entity. With @OnetoOne annotation, Hibernate will automatically create the foreign key constraint in the database to enforce this one-to-one relationship between these two entities.
Example 2:
Java
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String employeeName;
@OneToOne (mappedBy = "employee" )
private Address address;
}
@Entity
public class Address {
@Id
@GeneratedValue
private long id;
private int flatNumber;
private String street;
private String city;
private String state;
private int pincode;
@OneToOne
@JoinColumn (name = "id" )
private Employee employee;
}
|
Code Explanation:
In the above example, we are creating an Employee entity that consists of different fields such as id which is annotated with @Id and @GeneratedValue to generate the id automatically. After that, we are creating other fields for employee entities such as employee name and address. We are annotating the address field with @OnetoOne annotation and mapping it with the employee.
Then we are creating an entity for Address in which we are creating a field for id which is annotated with @Id and @GeneratedValue to generate the id automatically. After that, we are creating different fields for flat number, street, city, state, and PIN code for the address. Then we are creating an employee field which we are annotating with One to one to create a one-to-one association between employee and address entities.