✅ 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 transactioncommit()
, Hibernate executes aDELETE
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
Feature | detach()/evict() | delete()/remove() |
---|---|---|
Effect on DB | No change → row remains | Row is permanently deleted |
Effect on entity | Becomes detached, not tracked | Scheduled for deletion |
Use case | Stop tracking without deleting data | Remove 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.