Java.Hibernate.Medium.What is the difference between detach() and delete()?

Short Answer

  • detach(): removes an entity from the current persistence context — it becomes detached, but stays in the database.
  • delete() (or EntityManager.remove()): marks the entity for deletion from the database, and after commit, its row is permanently removed.

🔎 Detailed Explanation

🔹 detach()

  • Detaches an entity from the first-level cache (persistence context) of the current Hibernate session or JPA EntityManager.
  • After detachment:
    • The entity is still a valid Java object in your application.
    • Hibernate no longer tracks changes to it → modifications won’t be flushed to the database.
    • The database row remains unchanged.
  • In JPA: entityManager.detach(entity)
    In Hibernate: session.evict(entity) (equivalent to detach).

Example:

MyEntity entity = session.get(MyEntity.class, 1L);
session.evict(entity); // Equivalent to detach
entity.setName("Won't persist!"); // Changes ignored on flush/commit

🔹 delete()

  • Schedules the entity for deletion in the database — after flush() or transaction commit(), Hibernate executes a DELETE SQL statement to permanently remove the corresponding row.
  • In JPA: entityManager.remove(entity)
    In Hibernate: session.delete(entity).

Example:

MyEntity entity = session.get(MyEntity.class, 1L);
session.delete(entity); // Schedules DELETE SQL → removes from DB on commit

📊 Quick Comparison Table

Featuredetach()/evict()delete()/remove()
Effect on DBNo change → row remainsRow is permanently deleted
Effect on entityBecomes detached, not trackedScheduled for deletion
Use caseStop tracking without deleting dataRemove data entirely

💡 Extra Insight: When to use them

✅ Use detach()/evict() when you want to avoid persisting further changes without affecting the database (e.g., memory management or skipping accidental updates).
✅ Use delete()/remove() when you want to permanently delete data from the database.

📌 Key Takeaways

detach() → entity stays in the database, but Hibernate stops tracking it.
delete() → entity is deleted from the database when transaction is committed.
✅ Detaching is about session/persistence context management, while deleting is about data removal.

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

Leave a Reply

Your email address will not be published.