---
title: "hibernate问题——a different object with the same identifier value"
author: "青蜂侠"
date: "2009-12-20T15:44:47Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-a-different-object-with-the-same-identifier-value"
draft: false
lastmod: "2009-12-20T15:44:47Z"
id: 552333
url: "https://brucefeng.iteye.com/blog/552333"
---

最近在项目中使用Hibernate时出现a different object with the same identifier value was already associated with the session。当时是A 对象内包含B和C对象，C对象中也包含B对象，session同时取出A对象和C对象，之后修改A对象之后session.update(A)出现 a different object with the same identifier value was already associated with the session的问题。在网上查了一下没有更好的解决方案，下面是找到的比较好的解决方法：

http://myreligion.iteye.com/blog/371103 写道

a different object with the same identifier value was already associated with the session。

　　错误原因：在hibernate中同一个session里面有了两个相同标识但是是不同实体。

　　解决方法一：session.clean()

　　PS：如果在clean操作后面又进行了saveOrUpdate(object)等改变数据状态的操作，有可能会报出"Found two representations of same collection"异常。

　　解决方法二：session.refresh(object)

　　PS：当object不是数据库中已有数据的对象的时候，不能使用session.refresh(object)因为该方法是从hibernate的 session中去重新取object，如果session中没有这个对象，则会报错所以当你使用saveOrUpdate(object)之前还需要判断一下。

　　解决方法三：session.merge(object)

　　PS：Hibernate里面自带的方法，推荐使用。

 同时可以参照http://opensource.atlassian.com/projects/hibernate/browse/HHH-509中的内容，可以找到很多有参照价值的内容。

个人在解决问题的时候使用了session.merge(object)，可以顺利解决问题。