Java.Hibernate.Medium.Explain cascading types like CascadeType.PERSIST and CascadeType.REMOVE.

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() or EntityManager.persist() on the parent, Hibernate also saves all associated child entities marked with CascadeType.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() or EntityManager.remove() on the parent, Hibernate also deletes all associated child entities marked with CascadeType.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

CascadeTypeDescription
PERSISTSave parent → automatically save children
MERGEMerge parent → merge children
REMOVEDelete parent → delete children
REFRESHRefresh parent → refresh children
DETACHDetach parent → detach children
ALLShortcut 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!

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

Leave a Reply

Your email address will not be published.