Hibernate – @PrimaryKeyJoinColumn Annotation
Last Updated :
21 Jun, 2023
@PrimaryKeyJoinColumn in Hibernate is used to specify the primary key of the associated entity as the foreign key of the current entity. This annotation is used to establish a one-to-one relationship between the two entities, where the primary key of one entity is considered the foreign key in another entity.
Examples for @PrimaryKeyJoinColumn Annotation
Example 1:
Java
@Entity
public class Student {
@Id
@GeneratedValue
private long id;
private String name;
@OneToOne
@PrimaryKeyJoinColumn
private Education education;
}
@Entity
public class Education {
@Id
@GeneratedValue
private long id;
private int sscPercentage;
private int hscPercentage;
}
|
Code Explanation:
In the above example, we are creating two entities for Student and Education details. These entities are having a one-to-one relationship with each other. The Student entity has a primary key column as id which is annotated with @ID and a field for education which is annotated with @PrimaryKeyJoinColumn. This annotation indicates that the education field will be used as a primary key of the Education entity as the foreign key. The Education entity has its own primary key as id and also contains other fields such as hoc percentage, and sec percentages. By using the @PrimaryKeyJoinColumn annotation, Hibernate will automatically generate the foreign key constraint in the database to establish the one-to-one relationship. It will ensure that the primary key value of the Education entity matches the foreign key value in the Student entity.
Example 2:
Java
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String employeeName;
@OneToOne
@PrimaryKeyJoinColumn
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;
}
|
Code Explanation:
In the above example, we are creating two entities for an Employee and Address. These entities are having a one-to-one relationship with each other. The employee entity has a primary key column as id which is annotated with @ID and a field for the address which we are annotating with @PrimaryKeyJoinColumn. This annotation indicates that the address field will be used as a primary key for the Address entity as the foreign key. The Address entity has its own primary key as an id and also contains other fields such as street, city, state, and PIN code. By using the @PrimaryKeyJoinColumn annotation, Hibernate will generate the foreign key constraint in the database to establish one to one relationship. It will ensure that the primary key value of the Address entity matches the foreign key value in the Employee entity.
Share your thoughts in the comments
Please Login to comment...