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.
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<Employee> 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<Employee> getEmployees() { return employees; }
public void setEmployees(List<Employee> 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; }
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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.