为什么hibernate返回一个代理对象? [英] Why is hibernate returning a proxy object?

查看:228
本文介绍了为什么hibernate返回一个代理对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用DAO的服务方法,然后从数据库返回一个对象。该方法从系统的许多部分调用。但是,一种特定的方法是获取类型为ObjectClass _ $$ _ javassist_somenumber的返回类型。这是抛弃的东西。我调用与其他地方完全相同的服务方法,那么为什么hibernate会返回代理而不是自然对象呢?

我知道有些方法可以暴露代理对象,但我觉得我不应该这样做。



查询很简单

  hibernateTemplate.find(from User你在哪里u.username =?,用户名)

我使用hibernate 3.3 btw。

解决方案

它是一个代理对象,用于支持延迟加载;基本上只要您通过accessor / getter方法引用子对象或查找对象,如果链接的实体不在会话缓存中,则代理代码将切换到数据库并加载链接的对象。它使用 javassist 有效地动态生成您的分级实施对象(尽管我认为它也可以配置为使用 CGLIB )。



如果它没有用这种方式代理,那么它就会很近 - 不可能实现无缝延迟加载。



我记不起无论您是否使用预先加载,然后是否会返回自然对象。我通常不会推荐使用急切加载,尤其是如果你有很多链接的子实体,因为它很快会成为一个巨大的性能瓶颈,因为它会将每个链接对象吸入到内存中。



另外,如果您需要区分类类型,而不是使用 obj.getClass(),请使用 Hibernate.getClass( obj)这会让你回到自然对象类,而不管它是否被代理过:查看Hibernate API Javadocs 这里


I have a service method that calls a DAO which then returns an object from the database. This method is called from numerous parts of the system. However, one particular method is getting a return type of ObjectClass_$$_javassist_somenumber as the type. Which is throwing things off. I call the service method exactly the same as everywhere else, so why would hibernate return the proxy as opposed to the natural object?

I know there are ways to expose the "proxied" object, but I don't feel like I should have to do that.

The query is simply

hibernateTemplate.find("from User u where u.username = ?", username)

I am using hibernate 3.3 btw.

解决方案

It is a proxied object in order to support lazy loading; basically as soon as you reference a child or lookup object via the accessor/getter methods, if the linked entity is not in the session cache, then the proxy code will go off to the database and load the linked object. It uses javassist to effectively dynamically generate sub-classed implementations of your objects (although I think it can be configured to use CGLIB too).

If it weren't proxied in this way it would be nigh-on impossible to implement seamless lazy loading.

I can't remember off the top-of-my-head whether if you use eager loading then whether the natural object would be returned instead. I wouldn't generally recommend using eager loading though especially if you have lots of linked child entities, as it can soon be a huge performance bottleneck as it will suck in every linked object into memory.

Also, if you need to discriminate on the class type, rather than using obj.getClass(), use Hibernate.getClass(obj) which will give you back the natural object class regardless of whether it is proxed or not: see the Hibernate API Javadocs here.

这篇关于为什么hibernate返回一个代理对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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