问题描述
在Hibernate会话期间,我加载了一些对象,并且由于延迟加载,其中一些对象被加载为代理。这一切都OK,我不想关闭延迟加载。
During 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.
但后来我需要通过GWT客户端发送一些对象(实际上是一个对象) RPC。碰巧这个具体的对象是一个代理。所以我需要把它变成真正的对象。我无法在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 to 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代理转换为真实的实体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!