在spring,hibernate,struts2框架整合中出現的no session問題

    最近在進行框架整合,no session問題頻繁出現,所以今天寫下本文,說一下我遇見的問題,希望可以對廣大同行有一點幫助。

在整合spring和hibernate時出現了一個很大的問題,就是在測試類中,頻繁出現一下問題:



org.hibernate.LazyInitializationException: could not initialize proxy - no Session


在查閱了一些資料後,知道了出現這個問題的原因主要在於使用了以下方法:

Emp emp=this.getHibernateTemplate().load(Emp.class,id);

這個通過繼承HibernateDaoSupport後調用的方法有一個特性,那就是在調用該方法時,由於懶加載(lazy)的原因,程序並沒有發送查詢語句,也就是並沒有與數據庫進行交互,所以並沒有值,而該方法的特性是調用方法後便關閉session,而當系統發出查詢時,session已經關閉了,所以出現了no session的異常。


對於該問題的解決方案,可以使用過濾器opensession的方法,以下爲代碼段:

在web.xml文件中配置:

<!--
放置session closed異常出現。
spring的session過濾器
-->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

這樣可以在與頁面交互式把session延長至web端,避免了session過早關閉的問題。

其實不用過於糾結測試類中出現問題,在實際操作中可以解決該問題就可以了,因爲·在測試類中我們很難在單獨調用該方法時延長session。

如果一定要解決測試類中的該問題,可以嘗試用其他方法延長session,在該session中調用load方法即可,以下爲代碼:

@org.junit.Test
public void saveB(){
Emp emp=new Emp();
emp.setEmpNo(1008);
emp.seteName("ff");
emp.setJob("老五");
emp.setHiredate(DateConverterUtils.String2Date("2017-10-11"));
emp.setSal(2000);

Emp mgr=this.empBiz.loadById(1001);
System.out.println(mgr);

emp.setMgr(mgr);
Dept d=new Dept();
d.setDname("sasa");
d.setDeptNO(2);
d.setLoc("sas");
Dept dept=this.deptBiz.find(d);
emp.setDept(d);

// Dept dept=this.deptBiz.loadById(1);
// emp.setDept(dept);

this.empBiz.save(emp);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章