如何在 Hibernate 中获取未代理且 EAGER 获取的对象?
我想加载一个对象并忘记它来自休眠!就是这样,我只是做一些事情:
MyClass myObject = MyClassDAO.getUnproxiedObject(objectID);
然后我有一个 myObj 的真实实例(而不是来自 Hibernate 代理),所有属性都使用数据库中的值设置,这样我就无法将它与手动创建的对象区分开来。
在此线程中,存在一个方法来创建未代理的对象,但它确实没有处理急于装载物体的问题,我认为这是实现我的最终目标所必需的。
对于那些想知道为什么我想要这样的对象的人,我需要使用 Gson 序列化为 Json,但我认为它对很多人来说还有很多其他用途。
I want to load an objet and forget that it comes from hibernate! That's it, I just do something as:
MyClass myObject = MyClassDAO.getUnproxiedObject(objectID);
and than I have a real instance of myObj (and not from a Hibernate proxy) with all attributes set with the values from the database, so that I can't distinguish it from a manually created object.
In this thread a method is present to create an unproxied object, but it does not treats the issue of eager loding the objects, what I suppose is necessary for achieving my ultimate goals.
For those who are wondering why would I want such objects, I need to serialize then to Json with Gson, but I think it would have many other uses for many people.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经过测试,我发现引用的帖子中给出的方法正是我想要的。
after testing I found out that the method given in the citted post did exactly what I was looking for.
Hibernate 在使用 GSON 渲染时不会取消代理的原因是 GSON 使用反射来序列化字段,而不是使用 Hibernate 对象的 getter。要解决此问题,您需要注册一个新的 TypeHierarchyAdapter,它将在 GSON 序列化时取消代理该对象。
这是我的方法:
这是 HibernateProxySerializer:
The reason hibernate doesn't de-proxy while rendering with GSON is that GSON uses reflection to serialize the fields rather than using the getters of the Hibernate object. To workaround, you need to register a new TypeHierarchyAdapter that will de-proxy the object as GSON is serializing.
Here's my approach:
Here's the HibernateProxySerializer:
使用
FetchType.EAGER
立即加载所有关系。特别是对于 JSON 序列化,如果您正在构建 Web 应用程序,请考虑对 HTTP 请求使用 OpenSessionInView 拦截器。Use
FetchType.EAGER
to eagerly load all the relations. Specifically for JSON serialization, if you are building a web application consider using an OpenSessionInView interceptor for your HTTP requests.