HibernateSystemException: a different object with the same identifier value was already associated w

来源:互联网 发布:windows 域管理 编辑:程序博客网 时间:2024/05/23 18:44

HibernateSystemException: a different object with the same identifier value was already associated with the session.

这个错误是因为在hibernate的session一级缓存中存在一个被缓存的对象A,并且有另一个不在一级缓存中的对象B和A的标识符相同,但是它们不是同一个对象,即引用不相同,所以会抛出此异常。

以下代码也会抛出异常:

Image i = new Image();

i.setId(1);

Image j = session.load(Image.class,1);

session.delete(i);

因为i和j都是Image对象,并且有相同的标识符1,但是在session中的对象j和不在session中的对象i是两个对象,它们的引用不相同。因此会抛出异常!

解决办法:可以用session.clear()清一下session缓存,再进行hibernate session相关的操作。

原创粉丝点击