3

Hibernate returns same entity from same request, but in one case it is proxied and in second case it is not. Why it is sometimes proxied and sometimes is not?

I have a hibernate query:

    String q = "From EntityCustomFields as ecf "
            + "left outer join fetch ecf.customFields "
            + "where ecf.fleetId=:fleetId and ecf.entityType=:et";

    Query query = s.createQuery(q);
    query.setInteger("fleetId", fleetId);
    query.setString("et", et.toString());
    EntityCustomFields res = (EntityCustomFields) query.uniqueResult();

in res variable I get a EntityCustomFields object.

First case: customFields property contains few members with type: CustomField_$$_jvste27_9f this looks like proxied object, but in request "fetch" used and as I understand hibernate should not proxy as uses eager fetch. Right?

In second case I use other value for et parameter and get customFields property members with type: CustomDDLField and this is not proxied!

It becomes even more strange as I know that same database entity in first case is proxied but in second case it is not.

One detail could be significant is the CustomDDLField extends CustomField

Pavlo Morozov
  • 1,872
  • 2
  • 20
  • 48

1 Answers1

1

Take a look at this answer.

The objects you see as proxies have probably already been loaded as proxies earlier in the same persistence context instance, so Hibernate continues to use them until they are evicted or persistence context is closed.

This is the desired behaviour, as it ensures that the same object instance is used in all cases as long as the object is managed.

Community
  • 1
  • 1
Dragan Bozanovic
  • 21,631
  • 4
  • 36
  • 100
  • Looks like you was right about objects was previously loaded with proxies. I find request within same session, and updated it to make these instances loaded eager instead of lazy. This fixed my initial issue with proxied objects. Though I was not able to get inside of PersistenceContext and check what exactly was stored there. Now I will think what solution to use to prevent this happen. Thanks! – Pavlo Morozov May 19 '17 at 13:55