Why is hibernate returning a proxy object?

后端 未结 3 1035
时光取名叫无心
时光取名叫无心 2021-02-02 03:09

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

3条回答
  •  [愿得一人]
    2021-02-02 03:41

    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.

提交回复
热议问题