使用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">
新闻热点
疑难解答