Java.Hibernate.Medium.How does Session.clear() work, and when would you use it?

Short Answer

Session.clear() detaches all persistent entities from the current Hibernate session, effectively resetting the persistence context.
After calling clear(), the session no longer tracks changes to any previously managed entities.

🔎 Detailed Explanation

  • Hibernate uses the persistence context (a first-level cache) inside a session to keep track of persistent entities and their state.
  • When you call session.clear(), Hibernate evicts all entities from the session’s cache:
    • They become detached: changes to them will no longer be tracked or persisted automatically.
    • Future flushes or commits won’t include modifications to those entities.
  • clear() is like a “soft reset” for the session: it doesn’t close the session, but empties its state.

📅 When to Use Session.clear()

Long-running sessions: When processing many entities in a loop, memory can grow because Hibernate keeps references in the persistence context → clear() periodically frees memory.
Avoid unexpected updates: When you want to discard pending, unflushed changes without rolling back the transaction, clearing ensures they won’t be persisted.
Start fresh within the same transaction: You can clear the session to avoid interference from old entity states when loading or updating new objects.


🧑‍💻 Code Example: Clearing in a Batch Loop

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for (int i = 0; i < 10000; i++) {
    MyEntity entity = new MyEntity();
    entity.setData("Row " + i);
    session.save(entity);

    if (i % 100 == 0) {
        session.flush(); // Write current batch to DB
        session.clear(); // Detach entities, free memory
    }
}

tx.commit();
session.close();

🔎 Here, clear() prevents the session from growing too large and consuming excessive memory during bulk inserts.

📌 Key Takeaways

Session.clear() detaches all entities, empties the persistence context, but keeps the session open.
✅ Use it in batch operations to avoid memory bloat.
✅ After clear(), objects must be reattached (e.g., via merge() or update()) if you want Hibernate to track them again.
✅ Helpful when you need a clean state in the same session.

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

Leave a Reply

Your email address will not be published.