一个关于Hibernate lazy的问题
利用Hibernate时意外报错:
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:134)
at com.entry.database.bean.OaLoginLink$EnhancerByCGLIB$a418b18d.getName(<generated>)
at test.Test.main(Test.java:145)
极端让我头痛,上网查察相关资料发明这样一个办理方法:
"org.hibernate.LazyInitializationException: could not initialize proxy"延迟抓取出的错,hb3对many-to-one的默认处理惩罚是lazy = "proxy",没有搞懂到底怎么回事,把所有many-to-one,one-to-one都加上lazy="false"…
这个要领理论上没错,可是会让人发生误解,使人觉得只是修改<set>中的lazy值,照做后措施依然会报错,看看下面的文章也许就大白了(留意最后一行赤色标志)!
lazy initialization
荟萃(不包罗数组)是可以延迟初始化的,意思是仅仅当应用措施需要会见时,才载入他们的值。
s = sessions.openSession();
User u = (User) s.find("from User u where u.name=?", userName,
Hibernate.STRING).get(0);
Map permissions = u.getPermissions();
s.connection().commit();
s.close();
Integer accessLevel = (Integer) permissions.get("accounts"); //Error!
因为在commit之前,permissions没有被用到,permission没有被初始化,而session被close了,导致permissions永远都无法load data.
办理步伐:吧最后一行一道session被提交之前.
配置:
<set name="names" table="NAMES" lazy="true" order-by="name asc">
<key column="group_id"/>
<element column="NAME" type="string"/>
</set>
==================================
在做Spring1.2 + Hibernate 3 + struts demo时候碰着一个问题,编辑用户数据时候
用com.jeedev.service.dao.hibernate.UserHibernateDao 中 public TSysuser getUser(int userid) { } 要领,老是不能正常显示编辑数据。详细表示为:
参考 com.jeedev.service.dao.hibernate.UserHibernateDao 第32-45行
java代码:
public TSysuser getUser(int userid) {
if (this.getHibernateTemplate() == null) {
System.out.println("error at there");
return null;
}
TSysuser edituser= (TSysuser) getHibernateTemplate().load(TSysuser.class, new Integer(userid));
System.out.println(edituser.getUsername());
System.out.println(edituser.getDeptno());
return edituser;
}
假如删除上面的
java代码:
System.out.println(edituser.getUsername());
System.out.println(edituser.getDeptno());
在点击编号,修改时候就会呈现错误:
2005-10-27 15:35:59,245 ERROR [org.hibernate.LazyInitializationException] – could not initialize proxy – the owning Session was closed
org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed
颠末在javaeye论坛各人一致认为 是hibernate lazy的原因
在WEB级别应用时候,会呈现意想不到的lazy错误,办理要领就是 配置 lazy="false" 例:
<hibernate-mapping>
<class name="com.jeedev.hb.TSysuser" table="t_sysuser" lazy="false">