Here is my code
@Entity
class Parent extends Person {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "father")
private List<Child> children;
// ...
public void addChild(Child c) {
children.add(c);
}
}
@Entity
class Child extends Person {
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "id")
private Parent father;
public Child() {
this(NoParent.getInstance());//
}
public Child(Parent p) {
super();
setParent(p);
}
// ...
}
@MappedSuperclass
class Person {
@Id
private Integer id;
private String name;
}
class MyParentService {
public void addChild(String name, Parent parent) {
Child c = new Child(parent);
c.setName(name);
parent.addChild(c);
em.getTransaction.begin();
em.merge(parent);
em.getTransaction.commit();// Here two children with same name but different ids are created ...
}
}
Each time I run it, two children are added to the database while I just want one !
What am I doing wrong ?
Java 6
JPA 2
Hibernate 3.6.8.GA
I read the Hibernate documentation which is really confusing and didn’t help me much.
Notice, I have found that ObjectDB had recently faced AND fixed the exact same bug.
(Hibernate guys why are you waiting for so long ??)
Nevertheless, here the solution I came up with :
STEP 1:
Create a fresh new child (ie in detached state) and call its setParent method to link to its parent.
STEP 2:
Persist this child.
STEP 3:
Make changes to child as you need and merge it later.
The solution is quite no elegant, but it works !
Next you’ll fetch your parent object, it will have the previously child(ren) linked to it manually.