您的位置:首页 > 运维架构 > 网站架构

SSH架构中Illegal attempt to associate a collection with two open sessions 问题

2010-10-25 16:40 447 查看
多对多关系表的save保存动作

hbm配置:

<set name="groups" table="MNG_GROUP_USER" inverse="false" lazy="true" cascade="save-update">
<key column="user_id"/>
<many-to-many column="group_id" class="MngGroup" />
</set>


BEAN保存部分代码:

public void saveBsdUser(BsdUser user,String[] ids){
if(ids.length>0){  // 关联组
Set<MngGroup> groups = new HashSet();
for(int i=0;i<ids.length;i++){
MngGroup group = (MngGroup)getHibernateTemplate().find(
"from " + MngGroup.class.getName()+ " where id=?", new Integer(ids[i])).get(0);
groups.add(group);
}
user.setGroups(groups);
}
try {
this.getHibernateTemplate().saveOrUpdate(user);
this.getHibernateTemplate().flush();
} catch (DataAccessException e) {
logger.error("Save error:" + e);
throw e;
// return null;
}
}


web.xml 中Session配置部分

<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>false</param-value>
</init-param>
</filter>


使用以上配置保存一个BsdUser对象时报错:

Illegal attempt to associate a collection with two open sessions

解决上面的问题,只需修改web.xml中OpenSession的属性配置

<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>


说明一下Open Session in View的作用,

如果是singleSession=true的话,
就是允许在每次的整个request的过程中使用同一个hibernate session,可以在这个request任何时期lazy loading数据。

如果是singleSession=false的话,就不会在每次的整个request的过程中使用同一个hibernate session,而是每个数据访问都会产生各自的seesion,等于没有Open Session in View。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐