GAE与JPA:更新实体

时间:2011-09-13 07:14:22

标签: java google-app-engine jpa

我在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);

我希望有type="2"的实体,但只有一个实体type="1": - (

3 个答案:

答案 0 :(得分:2)

这是正确的行为,让我解释一下(我假设您的所有代码都在相同的持久化上下文/事务中运行)。

# 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);

答案 1 :(得分:0)

这是因为merge会创建实体的新实例,从提供的实体复制状态,并管理新的副本。您可以找到有关合并与持久性here的更多信息以及有关它的完整讨论here

答案 2 :(得分:0)

我也面临着类似的问题。我把问题放在了()后面的Reresh()。

这将是:

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

这将确保JPA Cache中更新的实体使用更新的数据进行刷新。 希望这会有所帮助。