问题描述
在 Hibernate 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中找不到像materialize"这样的方法.
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 代理转换为真实的实体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!