我有一个已持久化的实体,并希望将其添加到新生成的父实体(尚未持久化)。如果我尝试保留父级,则会收到错误“传递到持久的分离实体:model.Child”。我想我必须以某种方式为 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();
}
}
最佳答案
一个选项是始终使用 EntityManager.merge。如果传递了一个新实体,它将被持久化,如果传递了一个分离的实体,它将被合并到当前的持久化上下文中。
关于java - Hibernate - 已持久化子项的 "detached entity passed to persist"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16987066/