解决HibernateException: Illegal attempt to associate a collection with two open sessions

来源:互联网 发布:php ext 编辑:程序博客网 时间:2024/05/16 09:40

在项目中遇到这个 HibernateException: Illegal attempt to associate a collection with two open sessions. 一查代码发现是因为在service中存在两个不同的hibernate session都同时引用了同一个collection对象,一个是load(),一个是saveOrUpdate().由于项目是以前的项目,所以代码很不规范,也很“庞大”(一个方法超过1000行),不想太伤筋动骨的修改。

于是找到了一个简单的修改方法: hibernate session 的 merge() 方法。hibernate3.0以上可以使用merge()来合并两个session中的同一对。

将原来的代码:

hbSession.saveOrUpdate(closureTask);
改作:

hbSession.saveOrUpdate(hbSession.merge(closureTask));
 搞定!!
0 0