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里面有了两个相同标识但是是不同实体。
(原因:
  
  

  因为在向数据库中修改数据时,先查询了一次。存在同一试题类型的不同对象中。这样就会报这样的错。
 

  我的解决是:
    
      将从页面得到的要修改的值,赋值到查询得到的实体对象,修改写入时,使用查询的那个实体。
)
网上所有的解决方案,包括:
(1)使用session.clean(),如果在clean操作后面又进行了saveOrUpdate(object)等改变数据状态的操作,有可能会报出"Found two representations of same collection"异常。
(2)使用session.refresh(object),当object不是数据库中已有数据的对象的时候,不能使用 session.refresh(object)因为该方法是从hibernate的session中去重新取object,如果session中没有这个对象,则会报错所以当你使用saveOrUpdate(object)之前还需要判断一下。
(3)session.merge(object),Hibernate里面自带的方法,推荐使用。

原文地址:https://www.cnblogs.com/ljq-0722/p/4140029.html