Reputation: 258
How to get old entity from entitymanager
in JPA?
Code:
Address address=em.find(Address.class,1); System.out.println("Name of Address: "+address.getAddressName); // China address.setAddressName("Russia"); Address address1=em.find(Address.class,address.getAddressId()); System.out.println("Name of Address: "+address1.getAddressName); //?????????
How can I get my answer as "China"?
Upvotes: 2
Views: 1307
Reputation: 180
em.refresh(address1)
should work as it refresh the objects state from database ("China") overwriting ("Russia") changes done to the object.
Variables address and address1 are reference to same object, so both address.getAddressName() and address1.getAddressName() returns "China".
Database still has old value until
em.merge(address);
em.flush();
is called.
Upvotes: 1
Reputation: 8332
DataNucleus is right, but I would advice to use a query with a query hint to bypass the cache instead of using a second instance of entityManager.
See http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Query_Options
Upvotes: 2
Reputation: 15577
Use a different EntityManager. Any particular EntityManager will only ever return a single object with a particular identity (cached in the L1 cache)
Upvotes: 4