作为Hibernate的新用户,我遇到了一个"已分离的实体,在尝试从实体中移除项目时会传递给#34; 例外{{{ 1}}。
我尝试添加List
以及以各种组合将级联类型更改为orphanRemoval=true
和/或MERGE
,但这并没有帮助。我的实体是:
DELETE
在交易中,我尝试有效地执行以下操作:
@Entity
public class User
{
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) // adding "orphanRemoval = true" doesn't help
@JsonManagedReference
private List<Application> applications;
}
@Entity
public class Application
{
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) // adding "orphanRemoval = true" doesn't help
@JsonBackReference
private User user;
}
@Entity
public class ServerApplication extends Application
{
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) // adding "orphanRemoval = true" doesn't help
@JsonManagedReference
private List<Instance> instances;
}
@Entity
public class Instance
{
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) // adding "orphanRemoval = true" doesn't help
@JsonBackReference
private ServerApplication server;
}
这导致:
// For some User's ServerApplication object:
serverAplication.getInstances().remove(0); // Attempt to remove an item from DB.
entityManager.persist(user);
如何正确注释属性以便能够执行持久删除项目,即在org.hibernate.PersistentObjectException: detached entity passed to persist: my.project.User
上调用remove
?
注意:添加新的List<Instance>
个对象并更新列表可正常工作;它只是导致问题的移除。
答案 0 :(得分:0)
我认为你应该在删除实例后保留serverAplication,而不是用户:
// For some User's ServerApplication object:
serverAplication.getInstances().remove(0); // Attempt to remove an item from DB.
entityManager.persist(serverAplication);