HibernateException: Illegal attempt to associate a collection with two open sessions
Session session=getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(user);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
提示原因是使用开启了两个Session。
但是代码是一用,一提交,一关闭,应该不会开启两个Session的。
后来发现又是因为懒加载的原因。
解决方法
将session.update(entity)方法改成session.merge(entity),merge方法是合并为一个session。
本文探讨了在使用Spring框架时遇到的HibernateException:Illegal attempt to associate a collection with two open sessions的问题。通过将session.update(entity)方法替换为session.merge(entity),解决了由于懒加载导致的错误。详细解释了错误原因及解决方案。

535

被折叠的 条评论
为什么被折叠?



