How can I unproxy a hibernate object, such that polymorphism would be supported?
Consider the following example. Classes A and B are two hibernate entities. B has two subtypes C and D.
List<A> resultSet = executeSomeHibernateQuery();
for(A nextA : resultSet) {
for(B nextB : nextA.getBAssociations() {
if(nextB instanceof C) {
// do something for C
} else if (nextB instanceof D) {
// do something for D
}
}
}
This code fails to execute either the C or D block, since the B collection has been lazy loaded, and all instances of B are Hibernate proxies. I'd like a way to unproxy each instance.
Note: I realize the query can be optimized to eagerly fetch all B's. I'm looking for an alternative.
Hibernate generates the proxy class as a subclass of your entity class. Since version 5.3, Hibernate uses Byte Buddy to generate it at runtime. In older versions, Hibernate used Javassist or CGLIB. The generated proxy intercepts all method invocations, checks if the proxied entity object has been initialized.
getStreet() , Hibernate will hit the database to fetch the values for the associated entity and initialize it. Hibernate also returns a proxy object when you ask for an entity using the load method instead of the get method of the Session class.
The JPA lazy loading mechanism can either be implemented using Proxies or Bytecode Enhancement so that calls to lazy associations can be intercepted and relationships initialized prior to returning the result back to the caller.
Hibernate. initialize(entity. getXXX()) will force the initialization of a proxy entity or collection entity. getXXX() as long as the Session is still open.
Here's our solution, added to our persistence utils:
public T unproxy(T proxied)
{
T entity = proxied;
if (entity instanceof HibernateProxy) {
Hibernate.initialize(entity);
entity = (T) ((HibernateProxy) entity)
.getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
Nowadays Hibernate has dedicated method for that: org.hibernate.Hibernate#unproxy(java.lang.Object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With