Hibernate – @OneToMany Annotation
Last Updated :
21 Jun, 2023
@OneToMany annotation in Hibernate is used to obtain one-to-many relationships between two entities. It is used to map a collection-valued association where a single instance of an entity is mapped to multiple instances of another entity.
Examples of @OneToMany Annotation
Example 1:
Java
@Entity
public class Section {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany (mappedBy = "section" )
private ArrayList<Student> studentList;
}
@Entity
public class Student {
@Id
@GeneratedValue
private long id;
private String name;
private String gender;
@ManyToOne
private Section section;
}
|
Code Explanation:
In the above example we are creating two entities one is for the Section and another is for Student. In the section entity, we are creating different fields for id, name, and an array list of students which we are annotating with @OneToMany which indicates that the one section will consist of multiple students. Then we are creating an entity for Student in which we are creating different fields for id, name as well as section. We are annotating the section with @ManyToOne which indicates that multiple students will be present in one section.
Example 2:
Java
@Entity
public class Department {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany (mappedBy = "department" )
private ArrayList<Employee> empList;
}
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
private String gender;
@ManyToOne
private Department department;
}
|
Code Explanation:
In the above example, we are creating two entities, one for employees and another entity for the department. In the Department, we are creating different fields such as id which we annotate with the @Id and @GeneratedValue to generate the id automatically. Then we are creating other fields such as department name and lastly create a field for the employees list present in that department. We are annotating this array list with @OneToMany and mapping it with the department. This indicates that the employees array list is mapped with a department on One to many relationship. The @OneToMany annotation also indicates that one department may consist of multiple employees. Then we create another entity for our Employees which consists of several fields such as id, name, age, gender as well as the department. We are annotating department fields with @ManyToOne which indicates that each employee is mapped to a department.
Share your thoughts in the comments
Please Login to comment...