Video in progress
When do you need `EntityManager.refresh()`, and how does it differ from `find()`?
If the entity is already in the persistence context, find() returns that copy without going to the database. refresh() always runs a SELECT and overwrites the managed entity's state with the values in the database, so unsaved changes are lost. You need it after a trigger, a default value or a bulk update.
📖 Answer
@Transactional
public void demo(Long id) {
Product p = em.find(Product.class, id); // SELECT
Product again = em.find(Product.class, id); // no SQL, the same object
// elsewhere (native SQL, a trigger) the price changed
em.refresh(p); // SELECT, p is updated
}
When you need it:
- the database sets a value itself: a trigger updates
updated_at, or there's aDEFAULTcolumn, and you need to see that value after saving.persist()+flush()+refresh()is the plain way (Hibernate's@Generatedannotation does this automatically); - after a bulk JPQL or native
UPDATE, to update a single entity in the context; - in a long-running process, to get the latest state before writing. Here you can also take a lock with
refresh(entity, LockModeType.PESSIMISTIC_WRITE).
Things to watch: refresh() works only on a managed entity and throws IllegalArgumentException for a detached object. If the entity has unsaved changes, they are silently discarded. Cascade applies too: associations marked CascadeType.REFRESH are re-read as well, which means many SELECTs on a large graph.
If you need to refresh many entities, instead of calling refresh in a loop it's cheaper to em.clear() and send the query again.
Sign up to mark studied questions and save your progress.