✅ Short Answer
- CascadeType.PERSIST → when you save the parent entity, Hibernate automatically persists associated child entities.
- CascadeType.REMOVE → when you delete the parent entity, Hibernate automatically deletes associated child entities.
🔎 Detailed Explanation
Cascading in JPA/Hibernate allows certain operations performed on a parent entity to automatically propagate to its associated child entities.
You configure it in your entity mappings using @OneToOne
, @OneToMany
, @ManyToOne
, or @ManyToMany
annotations, e.g.:
@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private List<ChildEntity> children;
🔹 CascadeType.PERSIST
- When you call
session.save()
orEntityManager.persist()
on the parent, Hibernate also saves all associated child entities marked withCascadeType.PERSIST
. - Without it, you’d have to manually persist each child, otherwise they’d stay transient and cause exceptions on flush.
🔹 CascadeType.REMOVE
- When you call
session.delete()
orEntityManager.remove()
on the parent, Hibernate also deletes all associated child entities marked withCascadeType.REMOVE
. - Without it, deleting a parent could leave orphaned child rows, causing referential integrity issues.
🧑💻 Code Example
@Entity
public class ParentEntity {
@OneToMany(mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
private List<ChildEntity> children;
}
@Entity
public class ChildEntity {
@ManyToOne
private ParentEntity parent;
}
// Usage:
ParentEntity parent = new ParentEntity();
ChildEntity child1 = new ChildEntity();
ChildEntity child2 = new ChildEntity();
parent.setChildren(List.of(child1, child2));
child1.setParent(parent);
child2.setParent(parent);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(parent); // PERSIST cascade → saves children automatically
tx.commit();
session.close();
// Later, to remove:
Session session2 = sessionFactory.openSession();
Transaction tx2 = session2.beginTransaction();
ParentEntity loadedParent = session2.get(ParentEntity.class, parent.getId());
session2.delete(loadedParent); // REMOVE cascade → deletes children automatically
tx2.commit();
session2.close();
📊 Quick Overview of Common Cascade Types
CascadeType | Description |
---|---|
PERSIST | Save parent → automatically save children |
MERGE | Merge parent → merge children |
REMOVE | Delete parent → delete children |
REFRESH | Refresh parent → refresh children |
DETACH | Detach parent → detach children |
ALL | Shortcut for applying all cascade types |
📌 Key Takeaways
✅ CascadeType.PERSIST helps avoid manual saves for child entities → simplifies code.
✅ CascadeType.REMOVE keeps data consistent by deleting dependent children automatically.
✅ Cascading ensures relationships stay consistent without boilerplate CRUD operations.
✅ Use cascading carefully: unintended cascades can cause unexpected database changes!