---
title: "Hibernate数据库查询出现的错误 "
author: "cuixuelei"
date: "2010-04-16T17:03:55Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2010-04-16T17:03:55Z"
id: 645756
url: "https://cuixuelei.iteye.com/blog/645756"
---

**错误：org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: \[com.blt.myoa.po.oaattendance.TbPersonnelInfo#12]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: \[com.blt.myoa.po.oaattendance.TbPersonnelInfo#12]**

**大体意思：两个session在同时操作一个Object.**

**出现的原因是：查询了一下对象，紧接着对该对象进行修改（update），结果出错了。**

**解决方法： hibernate后台update 换成 merge**

 

**下面是摘自javaeye上的文章：**

今天做了个测试，写了个测试用例来看看merge与update时控制台打印出来的日志有什么不一样。实体bean很简单，就id和name两个字段，接下来分别给出以下几种测试情形的控制台日志内容：

1\. 数据库记录已存在，更改person的name为一个新的name。

merge方法打印出的日志如下:  
Hibernate: select person0\_.id as id0\_0\_, person0\_.name as name0\_0_ from person person0_ where person0\_.id=?  
Hibernate: update person set name=? where id=?

update方法打印出的日志如下:  
Hibernate: update person set name=? where id=?

2\. 数据库记录已存在，更改person的name和数据库里对应id记录的name一样的值。

merge方法打印出的日志如下:  
Hibernate: select person0\_.id as id0\_0\_, person0\_.name as name0\_0_ from person person0_ where person0\_.id=?  
此处相对于第一种情形少了update的动作

update方法打印出的日志如下:  
Hibernate: update person set name=? where id=?

3\. 数据库记录不存在时，也就是你传的实体bean的ID在数据库没有对应的记录。

merge方法打印出的日志如下:  
Hibernate: select person0\_.id as id0\_0\_, person0\_.name as name0\_0_ from person person0_ where person0\_.id=?  
Hibernate: insert into person (name) values (?)  
如果没有对应的记录，merge会把该记录当作新的记录来插入。此处我很疑惑，因为我传得person实体对象里写明了id值的，它为什么还会做插入的动作呢？

update方法打印出的日志如下:  
Hibernate: update person set name=? where id=?  
2009-11-22 20:59:55,359 ERROR \[org.hibernate.jdbc.AbstractBatcher] - Exception executing batch:  
org.hibernate.StaleStateException: Batch update returned unexpected row count from update \[0]; actual row count: 0; expected: 1

以下的内容摘抄自网上：  
　　当我们使用update的时候，执行完成后，我们提供的对象A的状态变成持久化状态。  
　　但当我们使用merge的时候，执行完成，我们提供的对象A还是脱管状态，hibernate或者new了一个B，或者检索到 一个持久对象B，并把我们提供的对象A的所有的值拷贝到这个B，执行完成后B是持久状态，而我们提供的A还是托管状态。