java org.hibernate.ObjectDeletedException:已删除的实例传递给合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13059241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:21:43  来源:igfitidea点击:

org.hibernate.ObjectDeletedException: deleted instance passed to merge

javahibernatejpa

提问by onur

This is my remove method:

这是我的删除方法:

public void removeIletisimAdresi(Integer index){
              getUser().getIletisimBilgileri().remove(getUser().getIletisimBilgileri().get(index))
        }

this is my parent relation

这是我的父母关系

...

...

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity= IletisimBilgileri.class,  mappedBy = "user")
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<IletisimBilgileri> iletisimBilgileri = new ArrayList<IletisimBilgileri(0);

...

...

this is my child :

这是我的孩子:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "Kullanici")
private Users user ;

so if i call remove method and update parent like entityManager.merge(user),it throws an exception like this:

因此,如果我调用 remove 方法并像 entityManager.merge(user) 一样更新父级,则会引发如下异常:

Caused by: org.hibernate.ObjectDeletedException: deleted instance passed to merge: [com.medikalborsasi.model.IletisimBilgileri#]

引起:org.hibernate.ObjectDeletedException:已删除的实例传递给合并:[com.medikalborsasi.model.IletisimBilgileri#]

..

..

can you explain and help me how can i solve this problem?

你能解释一下并帮助我如何解决这个问题吗?

回答by kamlesh patel

i think issue is in the your code only,

我认为问题仅在您的代码中,

getUser().getIletisimBilgileri().remove(getUser().getIletisimBilgileri().get(index))

Your mapping must be in such a manner that if you remove one entity from hibernate leads to deletion of same entity from the others dependent entity. eg :

您的映射必须采用这样一种方式,如果您从休眠中删除一个实体,则会导致从其他依赖实体中删除同一实体。例如:

Class A
{
     /* List of B entity(child) */
     List<B> listOfB;

}

Class B
{
     /* reference of A(parent) */
     A a;
}

so if you call

所以如果你打电话

hibernateSession.delete(b);

should delete the reference of b from the list that present in A. You don't have to explicitly remove reference of B from the List in A. So as per your method you are doing

应该从 A 中存在的列表中删除 b 的引用。您不必从 A 中的列表中明确删除 B 的引用。因此,根据您正在执行的方法

getA().getListOfB.remove(getA().getListOfB().get(someIndex));

I hope this small example will clear your issue.

我希望这个小例子能解决你的问题。

回答by Zaw Than oo

Before an entity removed, this entity must be manage state. We can use some of the function merge, find, etc. Note :After EntityManageris closed, all the entities of its will be detached.

在删除一个实体之前,该实体必须处于管理状态。我们可以使用一些功能mergefind等等。注:EntityManager是封闭的,它的所有的实体将被分离。

public void remove(Person p) {
    Perosn p2 = em.merge(p);
    em.remove(p2);
}