懶載入未用就關閉sessio--n的異常---面試問的-org.hibernate.LazyInitializationException: could not initialize proxy -

瓜瓜東西發表於2014-04-19

org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed


package com.lyq.util;



 import org.hibernate.Session;


import com.lyq.model.Medicine;
/**
 * Lazy測試
 * @author Li Yong Qiang
 */
public class Test {
public static void main(String[] args) {
Session session = null; //宣告Session物件

//開啟第二個session
try {
//獲取Session
session = HibernateUtil.getSession();
//開啟事物
session.beginTransaction();
System.out.println("============================================");
System.out.println("第二次查詢:");
//查詢藥品
Medicine medicine = (Medicine)session.load(Medicine.class, new Integer(1));
//輸出藥品名稱
//提交事物
session.getTransaction().commit();
HibernateUtil.closeSession(session);
System.out.println("藥品名稱:" + medicine.getName());
} catch (Exception e) {
e.printStackTrace();
//出錯將回滾事物
session.getTransaction().rollback();
}finally{
//關閉Session物件

}
}
}

相關文章