Java.Hibernate.Beginner.What is one-to-many mapping in Hibernate?

A one-to-many mapping models a relationship where one entity instance is associated with many instances of another entity. This is the typical way to map hierarchical or parent-child relationships in a relational database and your Java entity model.

🔹 Example real-world scenarios:

  • A Department has many Employees.
  • A BlogPost has many Comments.
  • A Customer has many Orders.

🔹 How to map it in Hibernate (JPA annotations):
You use @OneToMany on the parent entity, typically with a List or Set of child entities.

Example: Department → Employee

@Entity
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 = new ArrayList<>();

    // getters and setters
}

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id") // foreign key in employees table
    private Department department;

    // getters and setters
}

🔹 How it looks in the database:

  • departments table with id primary key.
  • employees table with id primary key and department_id foreign key referencing departments.id.

🔹 Key features of one-to-many mapping:
@OneToMany(mappedBy = "department") tells Hibernate:

  • The department field in Employee owns the relationship.
  • Don’t create a join table — instead, use the department_id foreign key in employees.

cascade = CascadeType.ALL → saves, updates, or deletes child entities automatically when you perform these operations on the parent.

orphanRemoval = true → automatically deletes child records if they’re removed from the parent’s collection.

🔹 Managing the relationship in code:

Department department = new Department();
department.setName("Engineering");

Employee emp1 = new Employee();
emp1.setName("Alice");
emp1.setDepartment(department);

Employee emp2 = new Employee();
emp2.setName("Bob");
emp2.setDepartment(department);

// Add employees to department
department.getEmployees().add(emp1);
department.getEmployees().add(emp2);

session.persist(department); // cascades to save employees

🔹 Key points:
✅ One-to-many is always bidirectional: @OneToMany on parent ↔ @ManyToOne on child.
✅ In the database, it’s implemented using a foreign key in the “many” side’s table (e.g., employees.department_id).
✅ The mappedBy attribute ensures no join table — just a direct foreign key.

Key takeaway:
One-to-many mapping in Hibernate models a parent-child relationship where one parent entity relates to many child entities, backed by a foreign key, and mapped using @OneToMany / @ManyToOne.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.