I tried both the EJB3 book example and solution suggested by Aleksander. The book example doesn't work but Aleksander's code works.
Now I am thinking if we do
Item refreshedItem = entityManager.merge(item);
.
.
long time consuming code
.
.
//decission is taken the item should be refreshed with the data from database
entityManager.refresh(refreshedItem);
Then as Lievaart said there is a chance that the object is merged, a flush occurs and the refresh reads the merged data and not the previous data.
The other way in which undo can be implemented is by using a find query based on primary key.
public Item undoItemChanges(Item item) {
Item refreshItem = em.createQuery("Select i from Item i where i.pkCol = :ItemPK")
.setParameter("ItemPK", item.pkCol).getSingleResult();
return refreshItem;
}
Just after writing this code I checked on net, I found following article
http://weblogs.java.net/blog/guruwons/archive/2006/09/understanding_t_1.html check section "Getting fresh results from database"