Menu

One-to-Many and Many-to-One Mapping

One-to-Many and Many-to-One Mapping

Which Side Owns the Key

A department has many employees, and each employee belongs to one department. The foreign key sits in the employee table, so @ManyToOne is the owning side, and @OneToMany is the inverse side.

This bidirectional form is preferred. A one-to-many mapping with no matching many-to-one produces a join table or extra update statements, which is less efficient.

@Entity
public class Department {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department")
    private List<Employee> employees = new ArrayList<>();

    public void addEmployee(Employee e) {
        employees.add(e);
        e.setDepartment(this);
    }
}

@Entity
public class Employee {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "department_id")
    private Department department;
}

Code Explanation:

  • department_id in the Employee table holds the foreign key.
  • mappedBy = "department" marks Department.employees as the inverse side.
  • addEmployee() sets both sides. Hibernate saves only the owning side, but keeping both in sync prevents stale in-memory data.
  • @ManyToOne is eager by default, so FetchType.LAZY is set explicitly.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details