![]() |
VOOZH | about |
@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.
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.
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.