我有一个具有 ChildEntities ArrayList 的 TestEntity。他们加入了一个拥有的关系。我想从数据存储中获取实体,更新子实体中的 int 字段,然后交换两个子实体的位置。但是,一旦我交换实体,似乎对 int 字段的更新就被删除了。我是否不允许将 JDO 持久对象存储在临时变量中以进行交换?这是我的测试代码,后面是实体本身的定义。当我在调试器中单步执行代码时,只要我将第二个值复制到列表中的位置 0,我的 ChildEntity 就会被覆盖或重置或其他任何东西。恐怕我缺少一些关于 JDO 工作原理的东西。
@Test
public void testSwap() {
PersistenceManager pm = PMF.get().getPersistenceManager();
TestEntity te = new TestEntity();
pm.makePersistent(te);
te.getChildEntities().add(new TestChildEntity("a"));
te.getChildEntities().add(new TestChildEntity("b"));
long id = te.getId();
pm.close();
pm = PMF.get().getPersistenceManager();
te = pm.getObjectById(TestEntity.class, id);
List<TestChildEntity> children = te.getChildEntities();
for (TestChildEntity tce : children) {
tce.setFoo(3);
}
TestChildEntity temp = children.get(0);
children.set(0, children.get(1));
// after the above line executes, the object referred to by temp is overwritten/reset when i watch in debugger.
children.set(1, temp);
assertEquals(3, children.get(0).getFoo()); // these asserts will both fail.
assertEquals(3, children.get(1).getFoo());
}
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class TestEntity {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent(mappedBy = "parent")
private List<TestChildEntity> childEntities;
public List<TestChildEntity> getChildEntities() {
return childEntities;
}
public Long getId() {
return id;
}
public static void demonstrateProblemWithRemove() {
PersistenceManager pm = PMF.get().getPersistenceManager();
TestEntity te = new TestEntity();
pm.makePersistent(te);
te.getChildEntities().add(new TestChildEntity("a"));
te.getChildEntities().remove(0);
pm.close();
}
}
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class TestChildEntity {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value
= "true")
private String encodedKey;
@Persistent
@Extension(vendorName = "datanucleus", key = "gae.pk-name", value =
"true")
private String keyName;
@Persistent
private int foo;
@Persistent
private TestEntity parent;
public TestChildEntity(String k) {
this.keyName = k;
this.foo = 1;
}
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}