这是我的代码
@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 ...
}
}
每次我运行它时,数据库中都会添加两个孩子,而我只想要一个!
我究竟做错了什么 ?
Java 6
JPA 2
休眠 3.6.8.GA