Cascading merge() leading to "Attempt to persist a reference to a non managed instance" error

#1

Dear Support

Using Objectdb 2.3.4_02 I ran into an exception while performing some tests with a parent/child relationship and cascading merge() operations. The parent has an application defined id, while the child's id is generated, but I don't know if this is of concern.

The following "test case" reproduces the error:

public final class ObjectDbCascadingMergeTest {

  public void go() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("objectdb:test.tmp;drop");
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();

    em.merge(new Child(new Parent("Joe")));
    em.merge(new Child(new Parent("Tim")));

    tx.commit();

    emf.close();
  }

  public static void main(String[] args) {
    new ObjectDbCascadingMergeTest().go();
  }

  @Entity
  public static final class Parent {

    @Id
    @SuppressWarnings("unused")
    private String name;

    public Parent(String name) {
      this.name = name;
    }

  }

  @Entity
  public static final class Child {

    @Id
    @GeneratedValue
    @SuppressWarnings("unused")
    private int id;

    @ManyToOne(cascade = CascadeType.ALL)
    @SuppressWarnings("unused")
    private Parent owner;

    public Child(Parent owner) {
      this.owner = owner;
    }

  }

}

The root cause is:

com.objectdb.o.UserException: Attempt to persist a reference to a non managed ObjectDbCascadingMergeTest$Parent instance - field ObjectDbCascadingMergeTest$Child.owner
at com.objectdb.o.MSG.d(MSG.java:61)
at com.objectdb.o.TYW.writeElement(TYW.java:249)
at com.objectdb.o.UMR$Q.y(UMR.java:960)
at com.objectdb.o.UMR.x(UMR.java:549)
at com.objectdb.o.UML.u(UML.java:515)

Forum threads with similar problems: 307 or 159

Thanks for your assistance.

 

#2

Thank you for reporting this problem. Cascading merge to new entity objects (the Parent instances in your code) is currently broken. This is also reported in issue #595 and hopefully will be fixed soon.

As a workaround - either use persist instead of merge:

    em.persist(new Child(new Parent("Joe")));
    em.persist(new Child(new Parent("Tim")));

or merge the parents explicitly with no cascading:

    Parent p1 = new Parent("Joe");
    em.merge(p1);
    em.merge(new Child(p1));
    Parent p2 = new Parent("Tim");
    em.merge(p2);
    em.merge(new Child(p2));

 

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login