问题描述
在休眠Session
期间,我正在加载一些对象,由于延迟加载,其中一些对象已作为代理加载.没关系,我不想关闭延迟加载.
During a Hibernate Session
, I am loading some objects and some of them are loaded as proxies due to lazy loading. It's all OK and I don't want to turn lazy loading off.
但是稍后我需要通过RPC将一些对象(实际上是一个对象)发送到GWT客户端.碰巧这个具体对象是代理.所以我需要将其变成一个真实的对象.我在Hibernate中找不到类似实现"的方法.
But later I need to send some of the objects (actually one object) to the GWT client via RPC. And it happens that this concrete object is a proxy. So I need to turn it into a real object. I can't find a method like "materialize" in Hibernate.
如何知道某些对象的类和ID,将它们从代理变为实物?
How can I turn some of the objects from proxies to reals knowing their class and ID?
目前,我看到的唯一解决方案是从Hibernate的缓存中逐出该对象并重新加载它,但这确实很糟糕,原因有很多.
At the moment the only solution I see is to evict that object from Hibernate's cache and reload it, but it is really bad for many reasons.
推荐答案
这是我正在使用的方法.
Here's a method I'm using.
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
throw new
NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
这篇关于如何将Hibernate代理转换为真实实体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!