Hibernate:org.hibernate.NonUniqueObjectException:具有相同标识符值的不同对象已与会话关联

时间:2013-02-21 15:24:56

标签: java hibernate hibernate-mapping

我想知道为什么会发生这种异常,尽管Hibernate get / query方法可以确保检索Hibernate会话中已经可用的对象,以防重复需要这些对象:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [x.y.z.MyObject#130062]
    at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:638)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:305)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:112)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)
    at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:252)
    at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392)
    at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335)
    at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
    at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:425)
    at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:362)
    at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:338)
    at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
    at org.hibernate.engine.Cascade.cascade(Cascade.java:161)
    at org.hibernate.engine.Cascade.cascade(Cascade.java:127)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.cascadeOnUpdate(DefaultSaveOrUpdateEventListener.java:376)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:350)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
    at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:57)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:742)
    at org.hibernate.impl.SessionImpl.update(SessionImpl.java:730)
    at org.hibernate.impl.SessionImpl.update(SessionImpl.java:722)

1 个答案:

答案 0 :(得分:2)

经过一些调试后,我发现我并没有停止在自我引用模型中级联传播更新:

type1 - > type2 - > type3 - >集合(TYPE1)

所以需要做的就是停止与cascade="none"级联:

<set name="type1collection" ... cascade="none">
...
</set>

这意味着,具有相同标识符值的另一个对象已经与会话相关联隐藏在自我引荐的子项中。这些孩子的额外更新是不必要的,因此没有级联是正确的。