问题描述
我通过服务将dao称为
I call dao from my service as
@Override
@Transactional
public Product getProductById(int id) {
return productDao.getProductById(id);
}
在dao中,我得到的产品为
and in the dao I am getting product as
@Override
public Product getProductById(int id) {
Product p = sessionFactory.getCurrentSession().load(Product.class, id);
System.out.print(p);
return p;
}
这很好,但是如果我将dao类更改为
This runs fine but if I change my dao class to
@Override
public Product getProductById(int id) {
return sessionFactory.getCurrentSession().load(Product.class, id);
}
我收到org.hibernate.LazyInitializationException:无法初始化代理-没有会话.例外发生在我只是在打印产品的视图层中.我不明白为什么在dao方法中在同一行中返回会导致视图层出现异常,但是如果我将其保存在引用中然后返回它,效果很好.
I get org.hibernate.LazyInitializationException: could not initialize proxy - no Session. The exception occurs in view layer where I am just printing the product. I do not understand why returning in same line in dao method results in exception in view layer but works fine if I save it in a reference and then return that.
推荐答案
在这里很好参考,以使您熟悉.get()和.load()方法的工作方式.
Here's a good reference to get you familiar with how .get() and .load() method works.
@Override
public Product getProductById(int id) {
Product p = sessionFactory.getCurrentSession().load(Product.class, id);
return p;
}
默认情况下,
session.load()
返回一个代理对象,而无需访问数据库.如果表上没有任何记录,它基本上会返回NoObjectFoundError
,否则它将返回一个引用而不填充实际对象甚至不访问数据库.您上面的方法会返回一个代理,并且由于它还必须初始化您的对象,因此会话保持打开状态并填充了对象.
session.load()
by default returns a proxy object without hitting a database. It basically returns NoObjectFoundError
if there aren't any records on the table or else it will return a reference without populating the actual object or even hitting the database.Your above method returns a proxy and since it has to initialize the your object as well, the session remains open and object is populated.
@Override
public Product getProductById(int id) {
return sessionFactory.getCurrentSession().load(Product.class, id);
}
但是在第二种方法中,基本上没有任何初始化就返回了代理.此后会话将关闭,无需任何事先使用.这样就得到了错误.
But in your second method, basically a proxy is returned without any initialization. session is closed thereafter without any prior use. Thus you get the error.
希望有帮助
这篇关于Hibernate中的LazyInitializationException:无法初始化代理-没有会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!