problem on updating entity

View: New views
2 Messages — Rating Filter:   Alert me  

problem on updating entity

by jpaer :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

import javax.persistence.*;

......
//Step 1: Entity Person(name='old name') persisted into DB, verified below,
.....
q = createQuery("SELECT p from Person p");
java.util.List oldLlist = q.getResultList();
....

//Step 2: update the name
q = createQuery("UPDATE Person p SET p.name='new name'");
....
q.executeUpdate();
....
q = createQuery("SELECT p from Person p");
java.util.List newList = q.getResultList();
....

The problem is that at Step 2 the name updated to 'new name' in the DB record, but kept as  'old name' from the result list.

???

Thx!

Re: problem on updating entity

by James Sutherland :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

With JPA to do an update you read the object, then change it through its set methods, then commit the transaction.  Updates using update-all queries are normally reserved for batch type situations.

Your issue, assuming you are using the same EntityManager is that the first query loads the objects in the persistence context, the update-all is only updating the database, not the object, and your third query must return the same object.

You should edit the object, instead of execute update-all queries, that is how JPA is supposed to be used.

i.e.
people = em.createQuery("SELECT p from Person p");
java.util.List oldLlist = q.getResultList();
....

//Step 2: update the name

....
for (Person person : people) {
  person.setName("new name");
}

em.getTransaction().commit();


If you really want to use the update-all query, you could call clear() after to reset the persistence context, or get a new EntityManager.  If you are seeing stale data across transactions, it could be a caching issue, you may need to invalidate, clear, or disable the shared cache.