A different object with the same identifier value was already associated with the session

异常信息

 A different object with the same identifier value was already associated with the session

A different object with the same identifier value was already associated with the session

这个错误的意思就是在Hibernate的session中存在了两个对象去标记同一个实体

代码分析

A different object with the same identifier value was already associated with the session

实体创建的代码:

A different object with the same identifier value was already associated with the session

由于这些实体都是新创建的,准备新建一批数据记录写入表中,但是由于新建的实体,是游离状态,新建 new 出来的实体 id 默认为0,所以在这里实际上是保存了一堆id为0的实体,Hibernate会将这些都认为是同一实体的多个对象,故抛出此异常。


尝试一:

于是乎,修改为以下,不会一起保存,把保存操作放在for循环里面

A different object with the same identifier value was already associated with the session

但是,只是第一个实体可以保存成功,后续的实体还是会抛出此异常。


尝试二:

将新建实体与保存操作一起执行。

A different object with the same identifier value was already associated with the session


这样还是不行。。。


解决方案

Hibernate升级之后,在批量保存时,需要确保主键唯一,最终以配置告终

A different object with the same identifier value was already associated with the session

IDENTITY:主键由数据库自动生成(主要是自动增长型) 

identity:使用SQL Server 和 MySQL 的自增字段,这个方法不能放到 Oracle 中,Oracle 不支持自增字段,要设定sequence(MySQL 和 SQL Server 中很常用),等同于JPA中的INDENTITY;


增加了这个配置之后,其实上述的几种尝试以及最终的代码都是可行的

Hibernate升级导致)