3

In our project we have a part of code that does things based on the class of the passed object. Something like this:

public class A { }
public class B extends A { }

public class Manager {
    public void manageA(A obj) {
        if(A.class.equals(obj.getClass()) {
            //do stuff
        } else if(B.class.equals(obj.getClass()) {
           //do other stuff
        }
    }
}

Now, A and B are Hibernate entities. Sometimes it happens the method manageA receives a proxied object and it fails to do stuff the way it's implemented. So we added a Hibernate.unproxy to get the unproxied object.

    public void manageA(A obj) {
        obj = (A) Hibernate.unproxy(obj);
        if(A.class.equals(obj.getClass()) {
            //do stuff
        } else if(B.class.equals(obj.getClass()) {
           //do other stuff
        }
    }

But I was afraid this might have some side effects, that is something that could work with a proxied object does not work anymore. I have noticed, by debugging, that when unproxing the object I lose the "handler" attribute (which is from Hibernate) but I don't know what it does or if Hibernate still handles its stuff in other ways.

I am aware i can just do this

    public void manageA(A obj) {
        Class<? extends A> clazz = (A) Hibernate.unproxy(obj).getClass();
        if(A.class.equals(clazz) {
            //do stuff
        } else if(B.class.equals(clazz) {
           //do other stuff
        }
    }

leaving the proxied object untouched. But I think whether or not unproxing an Hibernate object has some side effects it's something worth knowing for the future.

It's worth mentioning that I am not afraid of what happens outside the method but what might happen inside the method itself (let's say it calls save or refresh from a Spring Data JPA repository and something that could work with a proxied object does not work with an unproxied object)

valepu
  • 3,136
  • 7
  • 36
  • 67
  • 1
    AFAIK Hibernate is still able to work with unproxied entities that you feed to it and in effect certain queries just return unproxied entities (depends on your mapping as well). Unproxying an entity does neither change the entity nor the proxy, it just returns the entity "packed" inside the proxy. One thing that could happen though is that if the proxy would refer to a not yet initialized object that entity would get loaded (i.e. lazy loading). For more info have a look here: https://vladmihalcea.com/how-does-a-jpa-proxy-work-and-how-to-unproxy-it-with-hibernate/ – Thomas Sep 18 '19 at 14:12

1 Answers1

0

I have extensively used my code with Hibernate.unproxy since i posted this question and had no issue whatsoever.

As said in the comments Hibernate can handle unproxied entities just fine but it might trigger entity loading if you unproxy a not yet initialized object (like a child object that was lazy loaded).

valepu
  • 3,136
  • 7
  • 36
  • 67