---
title: "update时出现 adifferent object with the same identifierm value was already ..."
author: "siemenew"
date: "2010-07-12T15:01:32Z"
tags: []
categories: ["企业架构"]
slug: "update-adifferent-object-with-the-same-identifierm-value-was-already"
draft: false
lastmod: "2010-07-12T15:01:52Z"
id: 710690
url: "https://siemenew.iteye.com/blog/710690"
---

这两天在做一个练习项目时的更新模块时遇到一个问题，因为更新前要判断其中的一个属性值是否有重名，该属性的值重名有两个情况：
一种是与另外一个对象或另一条数据库记录重名，这种情况下只要改变该属性得值使得其唯一再用update(object)就没有什么问题。
另一种情况是该属性得值没有发生变化，用该属性值从数据库加载上来的对象与需要update的对象具有相同的标识（id值相同），此时执行update(object)时就会报以下错误：a different object with the same identifier value was already associated with the session。

这个错误的意思是说在session存在有相同标识的持久化对象，因此无法更新，一开始我的注意力放在如何把另外一个对象从session中去掉，结果试了很多方法都无法圆满的解决。

后来在查看HibernateTemplate的的方法时发现merge方法
merge(Object entity) ： Copy the state of the given object onto the persistent object with the same identifier.

用这个方法代替update问题得到解决。

<span style="color:red">看来merge方法仅仅是把对象拷贝到session并更新数据库，而对象还是处于脱管状态。</span>