在休眠中删除相关的对象 [英] Deleting of related objects in hibernate
问题描述
我有一个有两个类的hibernate模型,比方说A和B. B对A有多对一的引用。
I have a hibernate model with two classes, let's say A and B. B has a many-to-one reference to A.
我查询单个A和一个B对象。这些从会话中分离出来,并在某处/其他地方处理。 B.A属性是一个懒惰的代理。过了一会儿,A和B都需要被删除。我创建了一个新的Session并调用 .delete(A)
和 .delete(B)
。
I query a single A and a single B object. These are detached from the Session and they get processed somewhere/used else. The B.A property is a lazy proxy. Sometime later A and B both need to be deleted. I create a new Session and call .delete(A)
and .delete(B)
.
删除A即可,但删除B会导致以下异常:
Deleting A is ok, but then deleting B causes the following exception,
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.xxx.hibernate.objects.B.A
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:95) [hibernate3.jar:na]
at org.hibernate.event.def.DefaultDeleteEventListener.deleteEntity(DefaultDeleteEventListener.java:272) [hibernate3.jar:na]
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:163) [hibernate3.jar:na]
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:74) [hibernate3.jar:na]
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:794) [hibernate3.jar:na]
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:772) [hibernate3.jar:na]
Diggin在删除期间看起来像是tho,完成,并且由于A首先被删除,B的删除未通过空检查。它认为它是一个引用是null,即使我传入的B对象被设置为非null。看起来它在内部会话状态中进行了一些查找,并找到了删除的A实例。
Diggin in the code it looks as tho during the deletion a nullability check is done, and because A was deleted first, deletion of B fails the null check. It thinks it's A reference is "null" even tho the B object I pass in it is set to not-null. Looks like it does some lookup in the internal Session state and finds the deleted A instance.
任何人都知道我可以如何解决这个问题?如果可能的话,我宁愿不依赖于删除的顺序,除非在B之前删除A基本上是由于某些原因我没有看到错误。
Anyone know how I can work round this? I would prefer not to rely on the ordering of the deletion if possible, unless deleting A before B is fundamentally wrong for some reason I'm not seeing.
我是也不完全确定为什么要删除一个空检查。
I'm also not entirely sure why a null check is required on a delete.
推荐答案
我想你必须删除所有的子在删除父母之前。我意识到你不想受到删除顺序的束缚,但我认为没有其他解决方法。
I think you have to delete all the "children" before you delete the "parent". I realise you don't want to be at the mercy of the order of deletions, but I don't think there's any other way around this.
只是一个想法,但是要看看在删除的每一步中实际到达数据库的内容。如果Hibernate设置为使用表的所有列(包括链接到A的外键)创建DELETE命令,则如果DELETE命令查找A键的NULL值,则DELETE命令将找不到任何内容。
Just an idea, but have a look at what is actually arriving in the database at each step of the delete. If Hibernate is setup to create a DELETE command using all the columns of the table, including the foreign key linking to A, then the DELETE command won't find anything if it's looking for a NULL value of the A key.
这篇关于在休眠中删除相关的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!