REW

How Does The Refresh Operation Affect The Entity Object In Managed State?

Published Aug 29, 2025 5 min read
On this page

In Java Persistence API (JPA) and its implementations like Hibernate, the refresh operation on a managed entity overwrites the in-memory state of the object with the most current data from the database. This effectively discards any unsaved modifications made to the entity within the current persistence context. The refresh method ensures the application has the latest version of the data, which is particularly critical in scenarios involving concurrent transactions or external database changes.

The lifecycle of a managed entity

To understand the impact of a refresh operation, it's essential to first grasp the concept of an entity's lifecycle and the persistence context.

**1. Persistence context and the first-level cache:**When you load an entity from the database using an EntityManager (e.g., entityManager.find()), it becomes a managed entity. It is associated with the EntityManager and resides in the first-level cache, also known as the persistence context. The EntityManager is responsible for tracking any changes made to this managed entity.

**2. The managed state and dirty checking:**In the managed state, the JPA provider performs "dirty checking." It compares the current state of the entity object in memory with the state it held when it was first loaded. If a transaction is committed, any detected differences result in an UPDATE SQL statement being executed against the database.

The effects of the refresh operation

When entityManager.refresh(entity) is called, the following actions occur:

  • Discards unsaved changes: The refresh operation acts as a reset button for the entity's in-memory state. Any modifications made to the entity object since it was loaded or last refreshed are immediately lost. The provider does not execute an UPDATE statement; it simply discards the in-memory changes and replaces them with data from the database.
  • Reloads from the database: The JPA provider immediately issues a SELECT statement to retrieve the latest data for that specific entity from the database. This bypasses the first-level cache to ensure the most current data is obtained.
  • Overwrites the in-memory entity: The data retrieved from the database is used to overwrite the fields of the managed entity object in the persistence context. The object's state is now a mirror of the database record at the time the refresh was executed.
  • Refreshes associated entities (optional): The refresh operation will cascade to associated entities if the relationship is configured with CascadeType.REFRESH. This allows you to update an entire graph of related objects from the database.

When to use refresh

The refresh operation serves several important purposes and is typically used in specific situations:

  • Handling optimistic locking exceptions: In a concurrent environment, another transaction might have updated the same database record you are working with. If your application uses optimistic locking (e.g., with the @Version annotation), the database will throw an OptimisticLockException when a conflicting change is detected. You can catch this exception and call refresh() to reload the entity with the other transaction's changes and either retry the operation or display a conflict to the user.
  • Ensuring fresh data in long-running transactions: For transactions that last for an extended period, the entity's data can become stale. Calling refresh() guarantees you are working with the latest data, which is especially useful when your application's business logic depends on data that could be modified by other users or processes.
  • Synchronizing with external changes: If database triggers or external applications can modify the data outside the control of your application's EntityManager, a refresh operation is necessary to pull these changes into your in-memory entity objects.
  • Discarding invalid changes: If a user cancels an operation or you need to roll back a specific entity's changes without rolling back the entire transaction, refresh provides a way to revert the in-memory object to its persisted state.

refresh vs. merge

A common point of confusion for developers is the difference between refresh and merge. While both methods deal with synchronizing entity state, they operate in opposite directions and on different entity states.

Aspect refresh merge
Data flow Database to persistence context. It pulls the latest state from the database into the in-memory managed entity. Detached entity to persistence context. It pushes the state from a detached entity into the persistence context, which is then used to update the database.
Entity state Operates on a managed entity to update its state from the database. Operates primarily on a detached entity to re-attach it to the persistence context.
Local changes Discards any pending modifications in the current persistence context. Preserves changes made to the detached entity and applies them to the database.
Purpose To ensure the application is working with the freshest version of an entity from the database. To re-incorporate changes from a detached entity back into the persistence context, preparing them for database synchronization.

In summary, refresh is a "pull" operation, and merge is a "push" operation.

A practical example

Imagine a multi-user application where a Product entity can be edited by different users.

  1. User A loads Product with ID = 101 and its name is "Laptop".
  2. User B, in a separate transaction, edits the same Product and changes its name to "Gaming Laptop".
  3. User A then attempts to edit the product, but their in-memory object is now stale. Before saving their changes, they can call entityManager.refresh(product).
  4. The refresh operation discards any changes User A might have made and reloads the Product entity. The product.getName() call will now return "Gaming Laptop," reflecting the latest state from the database.

This mechanism is crucial for preventing lost updates and ensuring data integrity in complex, distributed, and concurrent application environments.

Enjoyed this article? Share it with a friend.