Reputation: 43053
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
Upvotes: 0
Views: 1535
Reputation: 43053
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.
Upvotes: 1
Reputation: 14061
Are you by any chance persisting the child after the parent? Also, the best practice is to manage the linking of the objects only on the owning-side of the relationship (with both parent.addChild and child.setParent in one method), but this doesn't seems to matter in your case, as the objects are properly linked by the time the "merge" occurs. If none of these works, then you may be hitting this: https://hibernate.onjira.com/browse/HHH-5855
Upvotes: 2