Advertisement
Google Ad Slot: content-top
Hibernate One-to-Many Mapping
A One-to-Many relationship occurs when one entity is associated with multiple entities.
For example:
- One Department has many Employees.
- One Customer has many Orders.
@OneToMany(mappedBy = "department")→ Defines the One-to-Many relationship.cascade = CascadeType.ALL→ If aDepartmentis saved/deleted, all relatedEmployeeswill be affected.orphanRemoval = true→ If anEmployeeis removed from the list, it is also deleted from the database.- Helper Methods (
addEmployee,removeEmployee) → Ensure consistency betweenDepartmentandEmployee.
Output
Table name : department
| id | name |
|---|---|
| 1 | IT |
Table name : employee
| id | name | department_id |
|---|---|---|
| 1 | Alice | 1 |
| 2 | Bob | 1 |
Create Read Update Delete (CRUD):
In this guide, we will implement CRUD (Create, Read, Update, Delete) operations for a One-to-Many Mapping using Hibernate.
Department and Employee class mentioned above
Output