Advertisement

Google Ad Slot: content-top

Hibernate One-to-Many Mapping

~1 min read · Hibernate
On this page

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.
Department.java
import jakarta.persistence.*; import java.util.List; @Entity @Table(name = "department") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true) private List employees; // Constructors public Department() {} public Department(String name) { this.name = name; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } // Add Helper Method public void addEmployee(Employee employee) { employees.add(employee); employee.setDepartment(this); } public void removeEmployee(Employee employee) { employees.remove(employee); employee.setDepartment(null); } }
  • @OneToMany(mappedBy = "department") → Defines the One-to-Many relationship.
  • cascade = CascadeType.ALL → If a Department is saved/deleted, all related Employees will be affected.
  • orphanRemoval = true → If an Employee is removed from the list, it is also deleted from the database.
  • Helper Methods (addEmployee, removeEmployee) → Ensure consistency between Department and Employee.
Employee.java
import jakarta.persistence.*; @Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne @JoinColumn(name = "department_id", nullable = false) private Department department; // Constructors public Employee() {} public Employee(String name) { this.name = name; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
Main.java
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import java.util.Arrays; public class Main { public static void main(String[] args) { // Create Hibernate session SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Department.class).addAnnotatedClass(Employee.class).buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); // Create Department Department department = new Department("IT"); // Create Employees Employee emp1 = new Employee("Alice"); Employee emp2 = new Employee("Bob"); // Add Employees to Department department.setEmployees(Arrays.asList(emp1, emp2)); emp1.setDepartment(department); emp2.setDepartment(department); session.persist(user); // Hibernate will generate an INSERT SQL statement transaction.commit(); session.close(); sessionFactory.close(); System.out.println("Insert data successfully!"); } }

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

HibernateUtil.java
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Employee.class) .addAnnotatedClass(Department.class) .buildSessionFactory(); } catch (Throwable ex) { System.err.println("SessionFactory creation failed: " + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session getSession() { return sessionFactory.openSession(); // Opens a new session when needed } public static void shutdown() { sessionFactory.close(); // Close SessionFactory when the application shuts down } }
Main.java
import org.hibernate.Session; import org.hibernate.Transaction; public class Main { public static void main(String[] args) { // Create Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); // Create Department Department department = new Department("IT"); // Create Employees Employee emp1 = new Employee("Alice"); Employee emp2 = new Employee("Bob"); // Add Employees to Department department.setEmployees(Arrays.asList(emp1, emp2)); emp1.setDepartment(department); emp2.setDepartment(department); // Save Department (Employees will also be saved due to CascadeType.ALL) session.persist(department); transaction.commit(); session.close(); // Read session = HibernateUtil.getSession(); department = session.get(Department.class, 1L); System.out.println("Department: " + department.getName()); for (Employee emp : department.getEmployees()) { System.out.println("Employee: " + emp.getName()); } session.close(); // Update session = HibernateUtil.getSession(); transaction = session.beginTransaction(); department = session.get(Department.class, 1L); if (department != null) { department.setName("Engineering"); session.merge(department); } transaction.commit(); session.close(); // Delete session = HibernateUtil.getSession(); transaction = session.beginTransaction(); department = session.get(Department.class, 1L); if (department != null) { session.remove(department); // This will also delete employees due to CascadeType.ALL } transaction.commit(); session.close(); HibernateUtil.shutdown(); // Close sessionFactory } }

Output

Output