Java.Hibernate.Beginner.What is cascade in Hibernate?

Cascade in Hibernate specifies which operations performed on a parent entity should automatically propagate to its related child entities. It controls whether actions like save, update, delete, or refresh applied to one entity also affect its associated entities.

🔹 Why do we need cascading?
Without cascade, you’d have to manually save, update, or delete each associated entity → tedious and error-prone.
Cascading simplifies entity lifecycle management, especially in parent-child relationships.

🔹 How do you specify cascade?
Use the cascade attribute on JPA/Hibernate association annotations, like @OneToMany, @OneToOne, or @ManyToOne.

Example:

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees;

✅ Here, any operation on Department cascades to its Employee list.

🔹 Common cascade types:

  • CascadeType.PERSIST → automatically saves new child entities when the parent is saved.
  • CascadeType.MERGE → updates child entities when the parent is merged.
  • CascadeType.REMOVE → deletes child entities when the parent is deleted.
  • CascadeType.REFRESH → refreshes child entities when the parent is refreshed.
  • CascadeType.DETACH → detaches child entities when the parent is detached.
  • CascadeType.ALL → includes all of the above.

if i want to use number of them

@OneToMany(
    mappedBy = "department",
    cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}
)
private List<Employee> employees;

🔹 Example usage:

Department department = new Department();
Employee employee1 = new Employee();
employee1.setDepartment(department);
department.getEmployees().add(employee1);

session.persist(department); // with CascadeType.PERSIST → saves employee1 too!

🔹 Important notes:
✅ Cascading only applies within the same Hibernate session — it doesn’t automatically handle changes across multiple transactions.
✅ Always use cascading carefully: CascadeType.REMOVE on many-to-many relationships, for example, can lead to unintended deletions of shared entities.

🔹 Key points about cascade:
✅ Makes entity graphs easier to persist, update, or delete.
✅ Should match your business rules: e.g., deleting an order should also delete order lines? → use CascadeType.REMOVE.

Key takeaway:
Cascade in Hibernate propagates operations from a parent entity to its associated entities, simplifying persistence and maintaining consistency — but requires careful design to avoid unintended side effects.

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

Leave a Reply

Your email address will not be published.