JPA query returns proxied entities

假如想象 提交于 2019-12-24 06:38:55

问题


Suppose I have 2 entities, EntityA and EntityB.
EntityB is @OneToOne related to EntityA:

@Entity
public class EntityB {
    @OneToOne(fetch = FetchType.LAZY)
    private EntityA entA;

    // other stuff
}

When I load EntityB from DB, the corresponding EntityA (say entA1) is lazy loaded.
After that I load EntityA list by

   List result = entityManager.createQuery("select A from EntityA A")
                  .setFirstResult(start).setMaxResults(end).getResultList();

The result list contains both previously lazy loaded and proxied EntityA and normal materialized EntityAs such like:

EntityA
EntityA_$$_javassist_nnn   <--- entA1 which is loaded lazily earlier
EntityA
...

So my questions:
1) Is this an expected behavior? Where can I find apidoc info about that?
2) Can I entirely load proxied entities only or entirely load eagerly all of them? Not mixed.


回答1:


Yes, it's expected behavior. Hibernate does everything it can to have one and only one instance of an entity in the session. Since it already has a proxy to EntityA, stored in the session when you loaded EntityB, a subsequent query returning the same EntityA instance effectively return the same instance: the proxy already stored in the session.

You shouldn't care much about the fact that the list contains proxies. Calling any method on the proxy (except getClass()) will return the same thing as calling it on the unproxied entity.

AFAIK, that's what allows having collections of entities behaving correctly with attached objects, although the objects don't even have an equals() method.



来源:https://stackoverflow.com/questions/11776534/jpa-query-returns-proxied-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!