Ralph Jaus wrote:Hi Deepika,
that's a good observation. In fact, I think there is no guarantee that
em.refresh(em.merge(item)); // to undo changes in entity (refresh from db)
works as it was desired in EJB 3 in Action: The persistence provider my choose to synchronize the persistence context with the database right after em.merge(item) was performed (justification by spec see below) - though it's unlikely. Then em.refresh(...) would read the just updated data from database. It's safer to use
em.refresh(em.find(Item.class, item.id));
to undo the changes.
JPA spec 3.2.3 (Synchronization to the Database)
The state of persistent entities is synchronized at transaction commit. [...]
The persistence provider runtime is permitted to perform synchronization to the database at other times as well when a transaction is active.
em.refresh(em.find(Item.class, item.id));
another thought to above statement,
-refresh is to update entity
-find is used to attach entity (to get it to manage state)
but this also solves the purpose
item = em.find(Item.class, item.id);
we do not need to run refresh() in this case, and can save a db call.