1

I have problems updating entities in Googles App Engine.

EntityManager em = ... // constructed like in the doc

MyEntity myE = new MyEntity();
myE.setType("1");      // String
em.persist(myE);em.refresh(myE);

myE.setType("2");
em.merge(myE);em.refresh(myE);

I expect a entity with type="2", but there is only one entity with type="1" :-(

Thor
  • 6,607
  • 13
  • 62
  • 96

3 Answers3

2

That's the correct behaviour, let me explain (I assume that all your code runs in the same persistence context / transaction).

# This line sets the value in the in-memory object without changing the database
myE.setType("2");

# this line doesn't do anything here, as the entity is already managed in the current 
# persistence context. The important thing to note is that merge() doesn't save the 
# entity to the DB.
em.merge(myE);

# This reloads the entity from the DB discarding all the in-memory changes.
em.refresh(myE);
Augusto
  • 28,839
  • 5
  • 58
  • 88
0

I was facing similar issue too. My issue is solved after my put the Reresh() after Commit().

It would be something like:

em.getTransaction().begin();
//Code to update the entity
em.persist(myE);
em.getTransaction().commit();
em.refresh(myE)

This will ensure the updated entity in JPA Cache gets refreshed with the updated data. Hope this helps.

Fengzmg
  • 710
  • 8
  • 9
0

It's because merge creates a new instance of your entity, copies the state from the supplied entity, and makes the new copy managed. You can find more info on merge vs. persist here and a full discussion about it here

Community
  • 1
  • 1
Kris
  • 5,714
  • 2
  • 27
  • 47
  • 1
    This is true if the entity is detached or transient. If it's attached, merge returns the entity you're passing as argument (and merge isn't useful, since the entity is already attached). It's not clear from the OP's post if the last part of the code is in the same transaction as the first one. – JB Nizet Sep 13 '11 at 08:25
  • I guess the safe bet would be to use myE = em.merge(myE); – Kris Sep 13 '11 at 08:31