1. 程式人生 > >懶加載的解決方法(全)org.hibernate.LazyInitializationException: could not initialize proxy - no Session

懶加載的解決方法(全)org.hibernate.LazyInitializationException: could not initialize proxy - no Session

close 修改 logs part 部門 pan 問題 org gin

如下錯誤:org.hibernate.LazyInitializationException: could not initialize proxy - no Session

原因是懶加載的問題,因為hibernate的機制是當我們查詢一個對象的時候,在默認情況下,返回的只是該對象的普通屬性,當用戶去使用對象屬性的時候,才會向數據庫再一次查詢,可以這時session已經關閉了,無法對數據庫進行查詢。

舉例:在界面顯示雇員所在的部門名稱${loginuser.department.name }

解決方法:(強烈推薦方法三和方法四,如果是簡單解決可以采用方法一)

方法一:修改對象關系文件,在Department.hbm.xml中做如下修改:

<class name="Department" lazy="false" table="department">

方法二:不推薦。顯示初始化,在獲取Employee的地方,添加:

Hibernate.initialize(employee.getDept());

方法三:openSessionView,也就是說擴大session的作用範圍(這種方法不適合引入spring的時候)

不做處理前,session的作用範圍,僅僅在service處調用開始,service處結束。可以使用過濾器,擴大session的作用範圍,讓他在整個過程都可以起作用

public class MyFilter1 extends
HttpServlet implements Filter { public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { Session session = null; Transaction transaction = null; try { session = HibernateUtil.getCurrentSession(); transaction
= session.beginTransaction(); arg2.doFilter(arg0, arg1); // 這是在所有的請求往回返的時候,才會提交 transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } throw new RuntimeException(e.getMessage()); }finally{ //不能使用常規的關閉 HibernateUtil.closeCurrentSession(); } } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }

方法四:

懶加載的解決方法(全)org.hibernate.LazyInitializationException: could not initialize proxy - no Session