Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the proxied class from the proxy class?

Tags:

java

hibernate

I'm using Hibernate with proxies, and I get objects belonging to classes such as test.DBUser$$EnhancerByCGLIB$$40e99a2d.

Is there a Hibernate method to retrieve the base class (test.DBUser in this case) from the proxied class? I know about Hibernate.getClass(), but it takes an Object, while I'm looking for a method which takes as input a Class.

like image 320
Flavio Avatar asked Nov 24 '12 11:11

Flavio


People also ask

What is the proxy class?

A proxy class allows you to hide the private data of a class from clients of the class. Providing clients of your class with a proxy class that knows only the public interface to your class enables the clients to use your class's services without giving the client access to your class's implementation details.

What is hibernate proxy and how it helps in lazy loading?

Hibernate uses generated proxy classes to support lazy loading of to-one associations, and you can use it to initialize associations to other entities. As soon as you call a getter or setter method of a non-primary key attribute, Hibernate executes an SQL statement to fetch the entity object.

What is a Java proxy class?

A proxy class implements exactly the interfaces specified at its creation, in the same order. If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified.

What is the use of proxy object in hibernate?

By definition, a proxy is “a function authorized to act as the deputy or substitute for another”. This applies to Hibernate when we call Session. load() to create what is called an uninitialized proxy of our desired entity class. This subclass will be the one to be returned instead of querying the database directly.


2 Answers

While I really like the simplicity of the approach posted by Flavio, I can't use it in production code unless it's documented as supported. Also, if you call .getImplementation() on the LazyInitializer, it will force the initialization of the proxy if it isn't already, which is a negative performance impact. I've come up with this approach which addresses both of these concerns:

public static Class<?> getClassForHibernateObject(Object object) {
  if (object instanceof HibernateProxy) {
    LazyInitializer lazyInitializer =
        ((HibernateProxy) object).getHibernateLazyInitializer();
    return lazyInitializer.getPersistentClass();
  } else {
    return object.getClass();
  }
}
like image 81
Pavel Avatar answered Jan 18 '23 23:01

Pavel


I found out, it is easier than I thought: just call getSuperclass() on the proxied class to obtain the unproxied, original class. I'm not sure how general this is, but it appears to work.

like image 34
Flavio Avatar answered Jan 19 '23 01:01

Flavio