Hibernate – @MapsId Annotation
Last Updated :
21 Jun, 2023
@MapsId annotation in Hibernate is used to obtain a one-to-one relationship between two entities by mapping the primary key of one entity to the foreign key of another entity. This annotation is used when we have to use a shared primary key between two entities.
Examples for @MapsId Annotation
Example 1:
Java
@Entity
public class Student {
@Id
@GeneratedValue
@Column (name = "student_id" )
private long studentId;
private String studentName;
}
@Entity
public class Education {
@Id
@GeneratedValue
private long id;
private int sscPercentage;
private int hsscPercentage;
@MapsId ( "studentId" )
@JoinColumn (name = "student_id" )
private Student student;
}
|
Code Explanation:
In the above example, we are creating two entities. One entity for Students consists of several fields such as student id and student name. Student id is annotated with @Id which is a unique id and @GeneratedValue to generate it automatically. Similarly, we are creating one more entity for Education in which we are creating several fields such as id, sscPercentage, hsscPercentage, and a field for students to which we have to map these marks. For the student field, we are annotating it with @MapsId and passing the id for the student which we have created for the student entity. By using the MapsId annotation we are mapping a primary key of a student entity to the foreign key for the education entity.
Example 2:
Java
@Entity
public class Employee {
@Id
@GeneratedValue
@Column (name = "employee_id" )
private long empId;
private String employeeName;
}
@Entity
public class Address {
@Id
@GeneratedValue
private long id;
private String street;
private String city;
private String state;
private int pincode;
@MapsId ( "empId" )
@JoinColumn (name = "employee_id" )
private Employee employee;
}
|
Code Explanation:
In the above example, we are creating two entities. One entity for the Employee which consist of several fields such as employee ID and employee name. We are annotating employee id with @Id and @GaneratedValue to generate it automatically. Similarly we are creating one more entity for Address in which we are creating fields for id, street, city, state, PIN code and employee. We are annotating employee entity with @MapsId and passing the id for the employee which we have created in employee entity. By using MapsId annotation we are mapping primary key of Employee entity to the foreign key for the Address entity.
Share your thoughts in the comments
Please Login to comment...