org.hibernate.lazyinitialization例外 [英] org.hibernate.lazyinitialization exception

查看:107
本文介绍了org.hibernate.lazyinitialization例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


org.hibernate.LazyInitializationException:懒得初始化角色集合:pojo.Person.address,没有关闭会话或会话。

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

我正在使用Spring 3.0和Hibernate 3.6。

I am getting this exception and I'm using Spring 3.0 and Hibernate 3.6.

推荐答案

看起来你有一个名为Person的实体,它有一个延迟加载的映射地址集合?您已加载Person,其加载的会话现已关闭。

It looks like you have an Entity called Person which has a lazily loaded mapped collection of Addresses? You have loaded the Person and the session it was loaded in has now been closed.

会话关闭后,您尝试访问该地址集合并尝试Hibernate加载他们。但是,如果原始会话不再可用,则无法进行此操作。

After the session was closed you then attempted to access that collection of address and Hibernate attempted to load them. However, that is not possible if the original session is no longer available.

要访问地址属性,您有以下几种选择:

In order to access the address property you have a few options:


  1. 使用OpenSessionInView模式确保Hibernate会话在请求/响应周期内保持打开状态(因为您已经标记了Spring MVC I'我假设这是一个基于Web的操作)。这实际上将您的Hibernate会话范围限定为HTTP请求。

  1. Use the OpenSessionInView pattern to ensure that the Hibernate session is held open for the duration of the request/response cycle (Since you've tagged Spring MVC I'll assume this is a web based operation). This essentially scopes your Hibernate session to the HTTP request.

确保在会话关闭(提交事务)之前加载所有必需的属性。您可以使用

Ensure that all required properties are loaded before the session is closed (transaction committed). You can do this using

Hibernate.initialize(person.address)

Hibernate.initialize(person.address)

或编写使用左连接提取的HQL。这可能是这样的:

or by writing HQL that uses a left join fetch. This could be something like:

createQuery("from Person as person left join fetch person.address")

这将覆盖此查询的任何延迟加载配置,并确保初始化任何集合。

This will override any lazy loading configuration for this query only and ensure that any collections are initialized.

这篇关于org.hibernate.lazyinitialization例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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