Java.Hibernate.Medium.What is the difference between Session.evict() and Session.clear()?

Short Answer

  • Session.evict(entity) detaches a single specific entity from the current Hibernate session.
  • Session.clear() detaches all entities in the session at once by clearing the entire persistence context.

🔎 Detailed Explanation

Session.evict(Object entity)

  • Removes the given persistent entity from the session’s first-level cache.
  • After eviction, Hibernate stops tracking the state of that specific object.
  • The entity becomes detached, meaning changes won’t be saved automatically.
  • Useful when you want to free memory or avoid unintentional updates for just one object.

Example:

MyEntity entity = session.get(MyEntity.class, 1L);
entity.setName("Updated Name");
session.evict(entity); // Only this entity is detached
// Later session.flush() won't persist entity's change

Session.clear()

  • Clears the entire persistence context — all tracked entities become detached.
  • Like a “mass evict”: the session itself stays open, but it forgets all in-memory entities.
  • Commonly used in batch processing to reset session state and avoid memory issues.

Example:

session.clear(); // Detaches all entities, resets session cache

📊 Quick Comparison Table

Aspectevict()clear()
ScopeSingle entityAll entities
PurposeStop tracking one objectReset session’s persistence context entirely
Memory managementFree memory for one objectFree memory for all objects
Entity state afterDetachedDetached
Session statusStays openStays open

💡 Extra Insight: When to choose which

✅ Use evict() when:

  • You only need to remove one or a few entities to reduce memory or prevent accidental updates.

✅ Use clear() when:

  • You’re processing large batches and need to periodically free memory by detaching all objects.
  • You want to start fresh in the same session without closing/reopening it.

📌 Key Takeaways

evict() → detaches a single entity; clear() → detaches all entities.
✅ Both methods leave the session open, but control what the session tracks.
✅ Use them to manage memory, avoid unintentional updates, or reset session state.

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

Leave a Reply

Your email address will not be published.