【发布时间】:2011-08-04 05:50:27
【问题描述】:
我的双向关系设置如下:
class Child{
@ManyToOne
@JoinTable(name = "CHILDREN_WITH_PARENT",
joinColumns = {@JoinColumn(name = "CHILD_ID")},
inverseJoinColumns = {@JoinColumn(name = "PARENT_ID")}
)
private Parent parent;
}
class Parent{
@OneToMany(mappedBy="parent", cascade=CascadeType.ALL)
Set<Child> childrens = new HashSet<Child>();
public void persistOrMerge() {
EntityManager em = entityManager();
em.getTransaction().begin();
try {
if (em.contains(this))
return;
if (id == null || id == 0) {
this.setCreatedDate(new Date());
em.persist(this);
} else {
Parent prev = em.find(Parent.class, this.id);
if (prev == null) {
em.persist(this);
} else{
this.setCreatedDate(new Date());
em.merge(this);
}
}
em.flush();
em.getTransaction().commit();
} finally {
em.close();
}
}
}
在我的客户端我有以下代码(GWT + EntityProxy)
Set<ChildProxy> children = new HashSet<ChildProxy>();
if(childIsNew)
child = request.create(Children.class)
else
child = request.edit(oldChild)
children.add(child);
//If children are deleted, they are not contained in the set
//we are sending back to server
parent.setChildren(children)
parent.persistOrMerge();
此代码仅适用于添加新孩子。即使父类收到一个空的子集,从父类中删除子类也不起作用。 JOIN 表中的链接不会被删除。
你能告诉我哪里遗漏了什么吗?
谢谢!
【问题讨论】:
-
我的理解是,由于对象是由 entitymanager 管理的,它会删除它收到的新集合中不存在的子对象
-
你能展示一下 setChildren 究竟做了什么吗?我没有看到任何错误。
-
setChildren 是一个简单的访问器方法
-
public void setChildren(Set
children) { this.children = children; }