如何解决Hibernate的LazyInitializationException [英] How to solve Hibernate's LazyInitializationException

查看:54
本文介绍了如何解决Hibernate的LazyInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将CustomerEntity映射到数据库中的表 customers .它与订单地址有一对多的关系.现在,我用下一个代码的订单吸引客户:

I have CustomerEntity mapped to table customers in database. It has one-to-many relations to orders and addresses. Now I retreive customer with orders with next code:

DetachedCriteria criteria = DetachedCriteria.forClass(CustomerEntity.class);
criteria.add(Restrictions.eq("id", patientId));
criteria.createCriteria("orders", CriteriaSpecification.LEFT_JOIN).add(Restrictions.and(
          Restrictions.isNull("deletedDate"),
          Restrictions.or(Restrictions.isNull("old"), Restrictions.eq("old", BoolType.FALSE))));
CustomerEntity customer = queryDao.searchSingle(criteria);

QueryDAO:

public <T> T searchSingle(DetachedCriteria criteria) {
   return (T) criteria.getExecutableCriteria(getCurrentSession()).uniqueResult();
}

但是当我尝试调用 customer.getAddresses()时,会抛出下一个异常:

But when I try to invoke customer.getAddresses() next exception is thrown:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: , no session or session was closed

之所以会发生这种情况,是因为默认情况下,休眠不加载一对多实体.

It happens because by default hibernate isn't loaded one-to-many entities. How can I without modifying Customer entity retreive his addresses too?

推荐答案

当您在 session 不可用时尝试访问延迟加载集合或字段时,将发生此异常.我的猜测是-应用程序的后端加载数据并关闭会话,然后将这些数据传递给前端,例如在没有会话的情况下.

This exception occurs when you try to access the lazy-loading collection or field at the moment when session is not available already. My guess would be - the backend of your application loads data and closes the session, then you pass this data to frontend, for example, where there is no session already.

要解决此问题,有几种可行的方法:

To resolve this, there are several possible ways to go:

  • 热切加载.可靠但可能缓慢的解决方案;
  • 更改会话管理的完成方式.考虑适用于典型Web应用程序的策略每次请求会话.问题根据请求创建休眠会话包含的信息可能对您有用.
  • Eager loading. Reliable, but possibly slow solution;
  • Changing the way session management is done. Consider strategy session-per-request which is suitable for typical web application. The question Create Hibernate-Session per Request contains information might be usable for you.

有关其他会话管理策略的信息,请尝试阅读此Wiki页面

For information about another session management strategies, try reading this wiki page.

这篇关于如何解决Hibernate的LazyInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆