2009-04-23 75 views
1

我正在使用以下方法在hibernate.Pleas中唯一的懶惰初始化問題告訴我它是否可以工作。 由於某些原因,我必須在持久層強制執行中實現我的轉換。休眠在視圖中打開會話

public class CourseDAO { 

     Session session = null; 
    public CourseDAO() 
{ 

    this.session = this.session = HibernateUtil.getSessionFactory().getCurrentSession(); 

} 

    public Course findByID(int cid){ 


     Course crc = null; 
     Transaction tx = null; 
     try { 
      tx = session.beginTransaction(); 
      Query q = session.createQuery("from Course as course where course.cid = "+cid+" "); 
      crc = (Course) q.uniqueResult(); 
      //note that i am not commiting my transcation here.Because If i do that i will not be able to 
      //do lazy fetch 


     } 
     catch (HibernateException e) 
     { 
      e.printStackTrace(); 
      tx.rollback(); 
      throw new DataAccessLayerException(e); 
     } 

     finally 
     { 


     } 
     return crc; 
} 


} 

,並在過濾器,我使用的folling代碼

session = HibernateUtil.getSessionFactory().getCurrentSession(); 
    if(session.isOpen()) 
      HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); 

這是正確的做法? 它可以有任何問題

回答

0

你能解釋爲什麼你需要在你的倉庫中有你的交易嗎?問題在於它們會變得如此細緻,所以你不會從會話緩存中獲得任何優勢,然後你在那裏打開事務,但是在你的過濾器中關閉它。如果您在服務中訪問多個存儲庫會發生什麼情況?也許我不明白你的意思,但我認爲你需要重新考慮迫使你管理你的倉庫交易的原因

0

你什麼時候創建你CourseDAO?如果它是一個singleton bean或者其他比頁面視圖長的其他東西,它需要保留一個SessionFactory,並在需要時創建一個新Session,而不是保留一個Session。