Search code examples
javahibernatejpaormhibernate-mapping

Hibernate returning Proxy for previously loaded entity


I am getting entity proxy instead the real entity when I load from db an instance previously loaded.

The first time I load the instance is through a method thtat executes this code

getEntityManager().createQuery(cq).getResultList().get(0)

The second time the application executes this method

public T findById(Long id) {
    DetachedCriteria crit = DetachedCriteria.forClass(entityClass).add(
        Property.forName(IdentifiableEntity.ID_PROPERTY).eq(id));
    Criteria executableCriteria = getExecutableCriteria(crit);
    return (T) executableCriteria.uniqueResult();
}

When I call findById with an id for a entity already loaded then I get a entity proxy. But if call the function to get a new entity (not already loaded) then I get the real entity.

I don´t understand this behavioura and I have no idea where the problem could be.

This is important for me because a hierarchy of entities is defined and the code executes for parent entity class, not the child one. Then when I get the parent entity proxy the methods of entity child does not exist

Regards


Solution

  • If you want the unproxy version you could simply do this:

    Object unproxied = ((SessionImplementor)session).getPersistenceContext().unproxy(proxy);