大家好。
最近鄙人又遇到了一个hibernate的问题了。
HibernateException: Illegal attempt to associate a collection with two open sessions
先容在下说明下,在下的。实体类
重点在这里, 使用了 懒加载。
@ManyToOne(targetEntity=TBCustom.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="ins_Code")
public TBCustom getCustom() {
return custom;
}
public void setCustom(TBCustom custom) {
this.custom = custom;
}
然后在 insert的时候。
public boolean insert(T entity) {
Session session = sef.openSession();
boolean falg = false;
Transaction trans = session.beginTransaction();
try {
session.save(entity);
trans.commit();
session.flush();
session.clear();
session.close();
falg = true;
return falg;
} catch (Exception e) {
e.printStackTrace();
trans.rollback();
if (session != null) {
session.close();
}
return falg;
}
}
然后果断的。出现标题的这个错误。
原因。是使用开启了两个Session。 但是我都是一用,一提交,一关闭,不可能开启两个的。 那么就是因为这个懒加载的原因了。
解决方法。
将 session.save (entity);方法改成 session.merge(entity);
这样就OK了。 merge 方法是合并为一个session。 如此 问题解决。