Hibernate:使用merge()时防止删除孤儿。 [英] Hibernate: prevent delete orphan when using merge();

查看:80
本文介绍了Hibernate:使用merge()时防止删除孤儿。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表

$ p $ @ManyToMany(Fetch = FetchType.Lazy)
@JoinTable(。 ..inverseJoin ....)
公共列表< objects> getList()

当我执行dto.merge时,我可能不想初始化它。



Hibernate会自动删除所有关系,即使我没有指定delete_orphan。



我可以知道如何防止删除hibernate孤儿又名关系?



目前我必须在进行合并之前从数据库中检索/设置列表。 解决方案

该列表是实体状态的一部分,因为实体是该关联的所有者。

所以如果你合并了一个在bean中没有任何东西的分离实体,你告诉Hibernate:这是实体的新状态,它不包含任何对象了。
显然,Hibernate删除了实体和列表中以前包含的对象之间的关联。



我的猜测是你构造了一个新的实体实例,它到 merge(),而不是从会话中获取实体,修改它,然后将此实例传递给merge():

而不是:

  SomeEntity e = new SomeEntity(); 
e.setId(34L);
e.setFoo(newFoo);
e = session.merge(e);

您应该这样做:

<$ p $ SomeEntity e = session.get(SomeEntity.class,34L); p> SomeEntity e = session.get
e.setFoo(newFoo);
//如果实体被分离:
e = session.merge(e);

请注意,您的问题与删除孤立无关。删除孤立的意思是:如果我删除了paren和children之间的关联,那么应该自动删除这些子实体。


I have a list of object

@ManyToMany(Fetch=FetchType.Lazy)
@JoinTable(...inverseJoin....)
public list<objects> getList()

I might not want to initialize it when I execute dto.merge.

Hibernate will auto remove all the relationships, even I did not specify delete_orphan.

May I know how to prevent hibernate from deleting orphans aka relationship?

Currently I have to retrieve/set the list from DB before doing a merge.

解决方案

The list is part of the entity state, since the entity is the owner of the association.

So if you merge a detached entity which doesn't have anything in the bean, you're telling Hibernate: here's the new state of the entity, which doesn't contain any object anymore. So obviously, Hibernate deletes the association between the entity and the objects previously contained in the list.

My guess is that you construct a new entity instance and pass it to merge(), instead of getting an entity from the session, modifying it, and then passing this instance to merge():

instead of doing:

SomeEntity e = new SomeEntity();
e.setId(34L);
e.setFoo("newFoo");
e = session.merge(e);

you should be doing:

SomeEntity e = session.get(SomeEntity.class, 34L);
e.setFoo("newFoo");
// if the entity is detached:
e = session.merge(e);

Note that your problem has nothing to do with deleting orphan. Delete orphan means: if I remove the association between paren and children, then the child entities themselves should be deleted automatically.

这篇关于Hibernate:使用merge()时防止删除孤儿。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆