我有一个 1:n 相关的父子对象。用例是这样的,在我保留一个或多个子记录之前,我总是会保留一个父记录。当我保存孩子时,它总是尝试重新创建父记录,即使它已被保存。我该如何预防?
家长班:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Parent {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private long id;
...}
幼儿班:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Child {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private long id;
@Persistent
private Parent parent;
..}
保存代码:
Transaction tx = pm.currentTransaction();
try {
tx.begin();
pm.setDetachAllOnCommit(true);
pm.makePersistent(parent);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
...
Child child = new Child();
child.setParent(parent); // reference the saved parent
tx = pm.currentTransaction();
try {
tx.begin();
pm.setDetachAllOnCommit(true);
pm.makePersistent(child);
tx.commit(); // here the parent is saved again
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
执行时,我希望在子表上插入一个。但相反,我也看到了父母的插入。
问题解决了。原来我需要在我的类声明中有“可分离=真”:
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Child {