Java.Hibernate.Medium.What is Session.refresh(), and when should you call it?

Short Answer

Session.refresh(entity) reloads the state of a persistent entity from the database, overwriting any in-memory changes with the latest data in the database.


🔎 Detailed Explanation

  • When you load an entity into a Hibernate session, Hibernate keeps it in its first-level cache (persistence context).
  • If the entity’s data is modified outside Hibernate (e.g., by another application or direct SQL), your in-memory object can become stale.
  • Calling session.refresh(entity) forces Hibernate to:
    • Execute a SELECT query to reload the entity’s current state from the database.
    • Overwrite the in-memory fields of the entity with fresh database values.
    • Leave the entity in the persistent state (still tracked by the session).
  • Important: Any unsaved changes you made in memory to the entity will be discarded.

📅 When to Use Session.refresh()

✅ When you suspect the database has changed outside your Hibernate session (e.g., direct SQL updates, other systems modifying the same record).
✅ To ensure your application is using the latest data, especially in high-concurrency environments.
✅ Before performing logic that depends on up-to-date values (e.g., checking a current balance before transferring funds).


🧑‍💻 Code Example

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

MyEntity entity = session.get(MyEntity.class, 1L);
System.out.println("Old value: " + entity.getName());

// Imagine another app updates this row in the DB at this point

session.refresh(entity); // Forces SELECT to reload latest state
System.out.println("Refreshed value: " + entity.getName());

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

📊 Quick Comparison with Similar Methods

MethodPurpose
session.flush()Syncs in-memory changes → database
session.refresh()Syncs database → in-memory object

💡 Extra Insight: refresh() vs. lock()

  • refresh() actively reloads data from the DB, overwriting local state.
  • lock(entity, LockMode.NONE) reattaches a detached entity without querying the DB (no refresh of data).

📌 Key Takeaways

Session.refresh(entity) reloads an entity from the database, overwriting local changes.
✅ Use it to ensure you have the latest data, especially when other systems or transactions might change the database.
✅ Be careful: any unsaved local changes to the entity will be lost after refresh.

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

Leave a Reply

Your email address will not be published.