---
title: "出现 org.hibernate.NonUniqueObjectException 错误的解决方法"
author: "abeetle"
date: "2007-03-01T14:16:00Z"
tags: []
slug: "org-hibernate-nonuniqueobjectexception"
draft: false
lastmod: "2007-03-01T14:16:00Z"
id: 233888
url: "https://abeetle.iteye.com/blog/233888"
---

org.hibernate.NonUniqueObjectException:a different object with the same identifier value was already associated with the session

解释：在session中具有相同标识符的不同对象已经关联。在同一个session中关联了两个同ID的实体对象。

session里对一个Class不允许用两个ID相同，但是不相等（==）的Object  
这个在Open Session In view中很容易发生。有的说是session没有及时关闭的导致的。

在网上狂搜一通，总结的解决办法如下：

1.一个通常可用但是并不稳妥的办法：

             **Session.flush()** before save(or update)

           session.evict(objPO);或者在update之前session.clear();

2.出现在bidirectional many-to-many中， 把一边的cascade设为none就可以了（两边都设为save-update就会出现这个问题）。

等等

我一一试过，无效，而且改的东西都是我不想改的

**最后终于解决了**

**就是在update或delete时，要把所操作的对象findby出来，就OK了**

 **主要参考了一下程序，才茅塞顿开**

**引用：[http://flower-city.spaces.live.com/blog/cns!5CDF3197CFFC015F!123.entry](http://flower-city.spaces.live.com/blog/cns!5CDF3197CFFC015F!123.entry) 中的** 

**class A{}**

**class B{**

**private A many\_to\_one\_A;**

**}**  

**public void update\_A\_B(A a) {**

**B b=findByA(a);**

**update(b);**

**update(a);**

**}**

**错误原因：传进来的A是一个独立实体，加载B后，b对象会加载一个a在这个session中，如此在update(a)时，session重新加载并update，如此重复了，**

**解决办法：**

**public void update\_A\_B(A a) {**

**B b=findByA(a);**

**update(b);**

**a=b.getMany\_to\_one\_A();**

**update(a);**

**}**