SGroup ,SGroupPrv 一对多关系
在 SGroup .hbm.xml中部门配置
<set name="SGroupPrvs" inverse="true" cascade="all" lazy="true">
<key>
<column name="GROUPID" precision="22" scale="0"/>
</key>
<one-to-many class="com.news.Hibernate.SGroupPrv"/>
</set>
JAVA其中代码:
String groupid=request.getParameter("groupid");
System.out.print("组名id:"+groupid);
SGroup groups=groupManager.getSGroup(groupid);
groups.setGroupid(Integer.parseInt(groupid));
System.out.println("groupid:"+groups.getGroupid());
System.out.println("groupname:"+groups.getName());
System.out.print("是否实例化:"+Hibernate.isInitialized(groups));
if(!Hibernate.isInitialized(groups))
Hibernate.initialize(groups);
//Hibernate.initialize(groups.getSGroupPrvs());
Set<SGroupPrv> set=groups.getSGroupPrvs();
System.out.print("是否实例化:"+Hibernate.isInitialized(set));
if(!Hibernate.isInitialized(set))
Hibernate.initialize(set);
System.out.print("是否实例化:"+Hibernate.isInitialized(set));
System.out.println(set.size());
运行出现failed to lazily initialize a collection of role异常
主要原因是:SGroup 采用了延迟加载策略,根据主键搜索出SGroup 对象时,并没有把Set<SGroupPrv>集合一并的搜索出来,得用到时才加载Set<SGroupPrv>,当用到Set<SGroupPrv>集合时无法获取到SGroup 对象的主键值
解决方法:
1.web.xml中加入OpenSessionInViewFilter过滤机制
<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>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.把LOAD(**.class,主键)方法改成GET(**.class,主键)方法,根据主键得到对应的对象
3.观察项目中cglib所属哪个版本的,如果是cglib_2.1.3.jar版本请升级至cglib_2.2.jar