✅ 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
Aspect | evict() | clear() |
---|---|---|
Scope | Single entity | All entities |
Purpose | Stop tracking one object | Reset session’s persistence context entirely |
Memory management | Free memory for one object | Free memory for all objects |
Entity state after | Detached | Detached |
Session status | Stays open | Stays 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.