【Hibernate】org.hibernate.HibernateException: identifier of an instance of xxx was altered from .....

在一个保存业务数据的方法里面,有时会报错,有时候又正常,报错信息如下:

org.hibernate.HibernateException: identifier of an instance of com.entity.Attachment was altered from f65d63296e2a4070a7f2d168a31e9fa1 to 06bf0bea595e4ef4b283e823737af3cb
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:80)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:192)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:152)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

从报错信息看,是保存附件的时候有问题了(Attachment是附件的实体)。看一下业务逻辑,把一个业务单据复制一下,生成一个历史记录,所以附件也必须复制一份。
看代码:

// 从数据库中查出原有数据
List attachmentList = attachmentService.getAttachmentList();
// 整理数据
if (attachmentList .size() > 0) {
  attachmentList .forEach(a -> {
      a.setId(null);
      a.setBizId(newBizId);
  });
  // 重新保存一份
  iAttachmentService.save(attachmentList );
}

这段代码会报错,后来修改一下,改成如下代码:

// 从前端传来的数据中,取出附件信息
List attachmentList = saveData.getAttachmentList();
List newAttachmentList = new ArrayList();
// 整理数据
if (attachmentList .size() > 0) {
  attachmentList .forEach(a -> {
    Attachment newAttachment = new Attachment();
    // 一个工具类,org.springframework.beans.BeanUtils.copyProperties(source, target)
    BeanUtil.copyBeanProperties(a,newAttachment );
    newAttachment .setId(null);
    newAttachment .setBizId(newBizId);
    newAttachmentList.add(newAttachment );
  });
  iAttachmentService.save(newAttachmentList);
}

结果,没有再报上面的错误。

原因分析:原本的方法,遍历ArrayList的时候把ID set为null, save的时候会重新赋值,对于hibernate来说,原来的对象还是在session中的(清一下session可能行)

参考:
https://blog.csdn.net/dly120219891208/article/details/41244449
https://stackoverflow.com/questions/4179166/hibernate-how-to-fix-identifier-of-an-instance-altered-from-x-to-y

你可能感兴趣的:(【Hibernate】org.hibernate.HibernateException: identifier of an instance of xxx was altered from .....)