Hibernate - 避免LazyInitializationException - 从代理和会话中分离对象 [英] Hibernate - Avoiding LazyInitializationException - Detach Object From Proxy and Session

查看:101
本文介绍了Hibernate - 避免LazyInitializationException - 从代理和会话中分离对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyObject myObject = repositoryHibernateImpl.getMyObjectFromDatabase();
//transaction is finished, and no, there is not an option to reopen it
ThirdPartyUtility.doStuffWithMyObjectType( myObject );

在这一点上,您已经定义了懒惰和急切加载的内容,第三方实用程序将尝试调用你的myObject实例上的所有方法,这很好,因为你不想为延迟加载的属性返回任何东西,不幸的是它不返回null,它会抛出 LazyInitializationException

at this point you've already defined what is lazy and eager loaded, and the third party utility will try to call all of the methods on your "myObject" instance, this is fine because you don't want to return anything for the lazily loaded properties, unfortunately it doesn't return null, it throws a LazyInitializationException.

发生这种情况是因为您实际上正在调用Hibernate代理对象的方法,并且它知道它没有获取数据,并抛出一个异常。

This happens because you're actually calling the method on Hibernate's proxy of your object, and it knows that it hasn't fetched that data, and throws an exception.

甚至有可能使用null值获取底层对象,这样getter只返回null,并且不会引发异常?基本上分离对象,以便Hibernate根本不知道它。被延迟加载的对象的访问器必须返回null,它不能返回实际值,我们希望能够将实体转换为POJO,而不必创建一个看起来就像实体一样的对象,并且必须重新映射所有

Is it even possible to get the underlying object with null values so that a getter just returns null, and doesn't throw an exception? Basically detaching the object so that Hibernate is no longer aware of it at all. The accessor to the object that is lazily loaded must return null, it cannot return the actual values, we want to be able to convert the entity into a POJO without having to create an object that looks just like the entity and has to remap all the values.

推荐答案

假设你有一个领域,在getter中你可以:

Let's say you have a field, in the getter you could:

MyField getMyField() {
    if (Hibernate.isInitialized(myField)) {
        return myField;
    }
    return null;
}

从org.hibernate.Hibernate的javadoc:

From the javadoc of org.hibernate.Hibernate:


public static boolean
isInitialized(Object proxy):检查
代理或持久集合是否已初始化

public static boolean isInitialized(Object proxy): check if the proxy or persistent collection is initialized.

这篇关于Hibernate - 避免LazyInitializationException - 从代理和会话中分离对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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