liveBook · Manning

EntityManager#refresh()

As explained in Java Persistence with Spring Data and Hibernate epub

EntityManager#refresh() reloads an entity's state from the database, overwriting its current managed in-memory state and optionally applying a lock mode.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains SELECT-based overwriting, missing-row failure, transaction constraints, cascading, isolation, and generated-query costs.
Examples
Demonstrates refreshing an Item after a concurrent update and reloading User billing details through REFRESH cascading.
What it assumes
Assumes managed entities, persistence contexts, transactions, entity associations, and basic database isolation behavior.
What you can do after
Operate/configure refresh to restore database state, handle concurrent changes, and control association reloads with REFRESH cascading.
How it connects
Connects refresh to managed entities, persistence contexts, transactions, transaction isolation, cascading, and EntityNotFoundException.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.