I have a 1:n related parent and child object. The use case is such that I'd always persist a parent record before I persist one or more child records. When I save the child, it always attempt to re-create the parent record, even though it has been saved. How do I prevent that?
Parent class:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Parent {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private long id;
...}
Child class:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Child {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private long id;
@Persistent
private Parent parent;
..}
Saving code:
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();
}
When that executes, I am expecting an insert just on the child table. But instead I am also seeing an insert on the parent as well.
Problem solved. It turns out I need to have "detachable=true" in my class declaration: