Hibernate – @ManyToOne Annotation
Last Updated :
21 Jun, 2023
@ManytoOne annotation in Hibernate is used to create a many-to-one relationship between two entities. The @ManyToOne annotation indicates that the many instances of one entity can be associated with only one instance of another entity. When we annotate a field of the method with @ManyToOne annotation the Hibernate will create the many-to-one relation between these two entities. This annotation is used to map a single-valued annotation where multiple instances of one entity are associated with a single instance of another entity.
Examples of @ManyToOne Annotation
Example 1:
Java
@Entity
public class Section {
@Id
@GeneratedValue
private long id;
private String sectionName;
private ArrayList<String> studentsNameList;
@ManyToOne
private School school;
}
@Entity
public class School {
@Id
@GeneratedValue
private long id;
private String schoolName;
}
|
Code Explanation:
In the above example we are creating two entities for School and Section and these entities are linked with each other through many-to-one annotation. We are creating different fields in section entities such as id for the section which is annotated with @Id and @GeneratedValue to generate it automatically. Then we are creating a field for section name, students name array list which is an array of student’s names present in that section. Lastly, we are creating a file for the section which is annotated with @ManyToOne. @ManyToOne annotation indicates that the section entity is having a many-to-one relationship with the School entity. The @ManyToOne annotation is used to annotate the school field in the Section entity which indicates that the section belongs to a single school.
Example 2:
Java
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
private String gender;
@ManyToOne
private Department department;
}
@Entity
public class Department {
@Id
@GeneratedValue
private long id;
private String name;
}
|
Code Explanation:
In the above example, we are creating two entities, one for the Employee and another for the Department. The employee entity consists of different fields such as employee name, age, gender, and id which are annotated with @Id and @GeneratedValue to generate it automatically. Then we are creating one more field for the department which we are annotating with @ManyToOne which indicates the current employee is associated In many to one relationship with the Department entity. Then we are creating an entity for the Department which has fields such as id which is auto-generated as we are adding @GeneratedValue annotation to it. Then we are creating a field for the name of the department.
Share your thoughts in the comments
Please Login to comment...