2009-11-01 114 views
1

我正在編寫一個Web應用程序,允許用戶獲取員工的個人信息並對其進行編輯(電子郵件,電話,姓名等)。當我在服務器上部署應用程序時,如果嘗試編輯員工,偶爾會出現一條錯誤消息,提示「Hibernate會話已關閉」。我通過休眠與數據庫交談的代碼如下:會話中的休眠問題

/* 
* File: EmployeeMapper.java 
*/ 

package org.hibernate.employee; 

import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.Transaction; 

/** 
* This class represents the data mapper for an employee to the 
* database. 
*/ 
public class EmployeeMapper { 

    /** 
    * Constructs an EmployeeMapper object. 
    */ 
    public EmployeeMapper() { 
    } 

    /** 
    * Finds an employee in the database by the username specified. 
    * 
    * @param username the username to find 
    * @return the employee if the username is in the database, null otherwise 
    */ 
    public Employee findByUserName(String username) { 
     Session session = SessionFactoryUtil.getInstance().getCurrentSession(); 
     Transaction tx = null; 
     try { 
      tx = session.beginTransaction(); 
      Query q = session.createQuery("from Employee e where e.username='" 
        + username + "'"); 
      List results = q.list(); 

      for (Object o : results) { 
       Employee e = (Employee) o; 
       return e; 
      } 
     } catch (RuntimeException e) { 
      e.printStackTrace(); 
     } finally { 
        session.close(); 
      } 
      return null; 
    } 

    /** 
    * Updates the employee in the database by writing it to the database. 
    * 
    * @param employee the employee to update in the database 
    * @throws Exception 
    */ 
    public void updateEmployee(Employee employee) { 
     Session session = SessionFactoryUtil.getInstance().getCurrentSession(); 
     Transaction tx = null; 
     try { 
      tx = session.beginTransaction(); 
      session.update(employee); 
      session.getTransaction().commit(); 
     } catch(RuntimeException e){ 
      if(tx != null){ 
       tx.rollback(); 
      } 
      throw e; 
     } finally { 
     session.close(); 
     } 
    } 

} 

有沒有人對我應該做什麼有什麼建議?如果您需要發佈其他課程或文件以獲取有關此計劃的更多信息,請說明您需要什麼。

回答

1

我的猜測是,你在處理你的視圖(jsp/velocity/jsf)時得到了這個結果。 請閱讀Open Session in View文件,以徹底解釋問題。

1

當您遇到該錯誤時,您不在該代碼中。例如,findByUserName返回一個對象。 該對象具有與其他對象的連接,這些對象可能不會從數據庫中初始化。

  • 在會話處於打開狀態時,如果訪問未提取的數據,數據庫查詢會在您訪問數據時以靜默方式觸發以提取數據。這是懶惰模式
  • 一旦退出該方法,會話將關閉。任何嘗試訪問惰性數據都會觸發您提到的異常。

在您的例子,當你認爲只有上面的代碼中會談到數據庫中,也有可能來自外部訪問。您的問題有兩種解決方案:

  • 使用開放式會議的多功能查看模式在其他的答案解釋。請注意,它們有幾個與之相關的重大缺陷,因此您必須仔細權衡這些選項。
  • 確保您需要的所有數據在之前獲取,您的業務代碼將實體傳遞到表示層。這是我們最近三個應用程序一直在使用的方法。