使用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">