Why is hibernate returning a proxy object?

后端 未结 3 1038
时光取名叫无心
时光取名叫无心 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:43

    In my opinion this expression:

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

    Should always return POJO, not a proxy. This is because standard HQL/criteria returns non-proxied object, but objects of your original entity classes. This is different from lazy associations fetching:

    @Entity
    class X {
        @ManyToOne(fetch = FetchType.LAZY)
        private User user;
    }
    

    Getting X object from the db here, we will have a lazy proxy in X.user field (a proxied User instance).

    Now, it happens that doing from User where [...] you sometimes have POJO and sometimes proxy object. Usually this is because in some executions User object was first fetched from the db through associations (from X where [...] query was called first in given hibernate session). Having already (proxied) User instance, hibernate will reuse this instance even for your plain queries like from User where [...].

提交回复
热议问题