0

I guess I don't really understand bidirectional one-to-many relations.

I have a parent, a child-A and child-B class with bidirectional relations between Parent <-> Child-A <-> Child-B. I want to add a child-B to the child-B-list of the child-A, but on every try to merge the parent I get an dublicated key exception. So how do I add a new child-B.

class Parent {
    long id;

    @One-To-Many, MappedBy Parent, Cascade All, OrphanRemoval true
    list <child-A> childsA;

    ...

    setter + getter
}

and

class Child-A {
    long id;

    @Many-To-One, JoinColums parentId, Cascade PERSIT MERGE REFRESH
    Parent parent;

    @One-To-Many, MappedBy Child-A, Cascade All, OrphanRemoval true
    list <child-B> childsB;

    ...
    setter + getter
}

and

class Child-B {
    long id;

    @Many-To-One, JoinColums Child-A-id, Cascade PERSIT MERGE REFRESH
    Child-A child-A;

    ...
    setter + getter
}

How do I add a new child-B to child-A and merge the parent to save everything in the db? So far I've tried:

Parent p = entityManager.getParent();
Child-A ca = p.getChildsA.get(indexOfCa); // the index is known
Child-B cb = new Child-B ();

... // fill cb with information

ca.add(cb); // automatically fires cb.setChild-A(ca);
p.getChildsA.set(index, ca);
entityManager.merge(p);

But this causes a DublicatedKeyException. So what is the best practise to add a child-B object to an already persisted child-A-object from an parent-object?

I also have to say, only merge is possible (no save, saveOrUpdate or persist) and it is not possible to edit the entity-classes. The entities are generated by something like a factory and every change will be overwritten when building the project. And the pom-file is not editable. Also this is a Java EE web-application with many different frameworks like primefaces and omnifaces.

halfer
  • 19,824
  • 17
  • 99
  • 186
André Schmidt
  • 89
  • 1
  • 12

1 Answers1

0

Solved it by myself. The limit for auto generated primary keys on the mysql database where to low. So jpa run out of primary keys and tried to override existing keys. Increased the hibernate_sequence number and the exception was gone.

André Schmidt
  • 89
  • 1
  • 12