我用的是spring 4和hibernate4,我想用懒加载,但一直报org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: domain.ElecUser.elecRoles, no session or session was closed的错误,我的web.xml配置如下:
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
//在Action里获取关联数据
ElecUser user = userService.getUserByLogName(elecName);
Set<ElecRole> roles = user.getElecRoles();
/**
*说明:ElecUser与ElecRole是多对多的关系
*/
//判断当前用户是否分配了角色
if(roles.size()==0){//程序执行在这里就出错了
this.addActionError("您还没有分配角色,请与管理员联系!");
return INPUT;
}
后来我又尝试在service里用
Hibernate.initialize(user.getElecRoles().getElecRoles());
程序又报org.hibernate.HibernateException: collection is not associated with any session
在线等大神!!