问题
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