1

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.

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153

1 Answers1

4

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That's the problem. I am using getClass().getSimpleName() in managed bean (upper layer). So I don't want hibernate (or JPA) specific stuff to unwrap the proxy class. However I can unwrap the class by getClass().getSuperClass() for proxied entities, so I need to determine where the current entity proxied or not. Shortly how can I getClass() correctly? – Uluk Biy Aug 02 '12 at 12:00
  • You could unproxy the object if it's a proxy (Hibernate-proprietary code): `if (object instanceof HibernateProxy) { return ((HibernateProxy) object).getHibernateLazyInitializer().getImplementation(); }` – JB Nizet Aug 02 '12 at 12:03
  • 4
    Is there any JPA-API method for unboxing class of managed entities? – Askar Kalykov Jan 08 '14 at 05:17