Advertisement

Google Ad Slot: content-top

Hibernate Many-to-One Mapping

~1 min read · Hibernate
On this page

A Many-to-One relationship means many child records are associated with one parent record.This is the inverse of @OneToMany.

For example:

  • Many Employees belong to one Department.
  • Many Orders belong to one Customer.

Create Read Update Delete (CRUD):

In this guide, we will implement CRUD (Create, Read, Update, Delete) operations for a Many-to-One Mapping using Hibernate.


Department and Employee class mentioned One-to-Many

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", department); Employee emp2 = new Employee("Bob", department); session.persist(department); session.persist(emp1); session.persist(emp2); transaction.commit(); session.close(); // Read Session session = HibernateUtil.getSession(); Employee employee = session.get(Employee.class, 1L); System.out.println("Employee Name: " + employee.getName()); System.out.println("Department: " + employee.getDepartment().getName()); session.close(); // Update Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); Employee employee = session.get(Employee.class, 1L); if (employee != null) { Department newDept = new Department("HR"); session.persist(newDept); employee.setDepartment(newDept); session.update(employee); } transaction.commit(); session.close(); // Delete Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); Employee employee = session.get(Employee.class, 1L); if (employee != null) { session.delete(employee); } transaction.commit(); session.close(); HibernateUtil.shutdown(); // Close sessionFactory } }

Output

Output