Possible Duplicate:
Hibernate: different object with the same identifier value was already associated with the session
我正在使用 Hibernate 和 Struts 1。我的 Web 应用程序在一台计算机上运行,而我的 Hibernate 代码在另一台计算机上运行。我正在使用网络服务来访问数据库。我的问题是,当我尝试更新任何对象时,当我通过服务方法调用 commit 时,它会抛出“org.hibernate.NonUniqueObjectException”。
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [..emp#2]
我无法找到问题所在,但我认为当我检索对象进行编辑时,它会附加到 Hibernate session ,然后当我尝试更新时,它会在服务端创建一个新对象,因为我正在反序列化该对象,因此可能有两个具有相同标识符的对象。
有人知道这可能会发生什么吗?
最佳答案
您需要merge
在提交之前将分离的对象放回到 Hibernate Session 中。使用(旧的)HibernateUtil 类,您的代码将类似于:
final Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
// ...
session.merge(entity);
另请参阅here .
关于java - 如何使用 Hibernate session 提交非 session 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500708/