我有一个实体,它已经被持久化并希望将它添加到新生成的父实体(尚未保留) . 如果我试图坚持父母然后,我得到错误“分离实体传递给持久化:model.Child” . 我想我必须以某种方式为子节点调用“entityManager.merge()”而不是“entityManager.persist()” . 但我没有明确地称之为坚持 . 这由“cascade = CascadeType.ALL”注释处理 . 如果实体已经存在,我可以告诉hibernate以某种方式进行合并吗?
顺便说一句:如果我第一次坚持父,然后添加子,然后再次坚持父 - >它工作(但使我的应用程序逻辑更复杂) .
这是我的代码:
public class App
{
@Test
public void test()
{
// I have a child object (in the real app
//this is a user object and already persisted
Child child = new Child();
HibernateHelper.persist(child);
Parent parent = new Parent();
parent.addChildren(child);
// throws the exception "detached entity passed to persist: model.Child"
HibernateHelper.persist(parent);
Parent newParent = HibernateHelper.find(Parent.class, parent.getId());
assertEquals(1, newParent.getChildren().size());
}
}
我的“孩子”实体:
@Entity
@Table(name = "child")
public class Child {
public Child(){}
private Long id;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private Parent parent;
@ManyToOne
@JoinColumn
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
我的“父母”实体:
@Entity
@Table(name="parent")
public class Parent {
public Parent(){}
private Long id;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private Set<Child> children = new HashSet<Child>();
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
public Set<Child> getChildren() {
return children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
public void addChildren(Child child){
children.add(child);
child.setParent(this);
}
}
持久的帮助方法(对孩子来说看起来一样)
public static void persist(Parent entity){
EntityManager entityManager = null;
try {
entityManager = beginTransaction();
if(entity.getId()!=null){
entityManager.merge(entity);
}else{
entityManager.persist(entity);
}
entityManager.getTransaction().commit();
} catch (Exception e) {
System.out.println(e);
return;
}finally{
if(entityManager != null)
entityManager.close();
}
}
1 回答
一个选项是始终使用EntityManager.merge . 在传递新实体的情况下,它是持久的,如果传递了分离的实体,则将其合并到当前的持久性上下文中 .