EntityManager#refresh() reloads a managed entity from the database and overwrites its current in-memory state. Hibernate executes a SELECT, so changes made to the entity since loading are discarded; if the row was deleted, refresh() throws EntityNotFoundException. section 10.2.6
Use refresh() when the persistence context may contain stale or unwanted state:
- Refresh selectively in an extended persistence context that remains open across requests or user interactions, where database values can become stale. section 10.2.6
- Discard in-memory edits when a user cancels a conversation instead of waiting for normal transaction-commit conflict handling. section 10.2.6
- In an unsynchronized persistence context, use refresh() to reload current state; flushing changes or requesting a non-NONE lock still requires a transaction. section 11.3.1
- Account for transaction isolation: a refresh may not see another transaction's committed change under the current isolation level. section 13.1.3
Reloading a concurrently changed entity
Item item = em.find(Item.class, ITEM_ID);\nitem.setName("Some Name");\n// Another process changes the database row\nem.refresh(item);\nassertEquals("Concurrent UpdateName", item.getName());
Refreshing does not automatically refresh related entities unless the association enables CascadeType.REFRESH. With a User-to-BillingDetails association, cascading reloads each managed BillingDetails instance and reloads the collection, potentially issuing multiple SELECT statements. section 13.1.3
