org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
在写业务类代码的时候老是出现这个问题,从网上查了相关的资料解决了这个问题
这是业务类的代码
public Customers getCustomers() throws Exception
{
Session session = HibernateSessionFactory.currentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customers customer=(Customers)session.load(Customers.class,new Long(1));
// if(!Hibernate.isInitialized(customer))
// Hibernate.initialize(customer);
tx.commit();
return customer;
}catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally
{
session.close();
}
}
现把解决方案写下来:
1。因为返回的是代理对象,在查询中使用了load方法,但是这个方法在session关闭以后代理对象也就取不到值了,所以在我的dao层的时候,代理对象还没有关闭,在这个层设置一个临时变量,把返回的结果赋给临时变量就可以了。
2。另一种方法就是不用load方法,而改用get方法,就不会出现这种问题了。