When to Use @JoinColumn Annotation in Hibernate?
Last Updated :
21 Jun, 2023
The @JoinColumn annotation in Hibernate is used to specify the mapping of a foreign key column in a relationship between two entities. The @JoinColumn annotation is applied on the owning side of the association to define the foreign key column name and other attributes which are related to the join column.
Examples for @JoinColumn Annotation
Example 1:
Java
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String employeeName;
@ManyToOne
@JoinColumn (name = "department_id" )
private Department department;
}
@Entity
public class Department {
@Id
@GeneratedValue
private long id;
private int name;
}
|
Code Explanation:
In the above example, we are creating two entities for Employee and Department. The employee entity consists of different fields such as id for employee id, name, and department which we are annotating it with many-to-one and join columns. The many-to-one indicates that multiple employees can be associated with a single department. The Employee entity has a foreign key column that maps to the primary key of the Department entity. This mapping is obtained by using @ManyToOne and @JoinColumn annotations. With the help of @JoinColumnn annotation, Hibernate will generate the foreign key constraint in the database to establish the relationship between Employee and Department entity.
Example 2:
Java
@Entity
public class Student {
@Id
@GeneratedValue
private long id;
private String studentName;
@ManyToOne
@JoinColumn (name = "section_id" )
private Section section;
}
@Entity
public class Section {
@Id
@GeneratedValue
private long id;
private int name;
}
|
Code Explanation:
In the above example, we are creating two entities for Student and Section. The student entity consists of different fields such as id for the student if, name, and a section which we are annotating with many-to-one and join columns. The many-to-one indicates that multiple students can be associated within a section. The student entity is having a foreign key column that maps to the primary key of the Section entity. This mapping is obtained by using @ManyToOne and @JoinColumn annotations. With the help of @JoinColumn annotation, Hibernate will generate the foreign key constraint in the database to establish the relationship between the Student and Section entity.
Share your thoughts in the comments
Please Login to comment...