Lazy loading inherited entities guidance

I discovered that while bytecode enhancement allows lazy loaded entities to avoid use proxies, for inherited classes this is not the case - proxies are always used. These threads seem to say that this behavior is required to allow “getting the foreign key of an associated entity without fetching the entity”.

https://hibernate.zulipchat.com/#narrow/stream/132096-hibernate-user/topic/bytecode.20enhancement
https://hibernate.atlassian.net/browse/HHH-15737

Although from my perspective it would be nice to have no-proxy lazy loading, I understand that there are other considerations that make that undesirable.

My question is how should I deal with issues related to proxies for lazy-loaded entities. Here are two situations:

  • I have a proxy for a base-class entity and I want to cast it to a sub-class. This causes a class cast exception. I get around this by calling Hibernate.unproxy() to turn the proxy into a real entity before casting.
  • I have a proxy for an entity of unknown type and I want to get its underlying class. Currently, I’m using Hibernate.getClass(unknownEntity) to find the class.

Is that standard practice? Are there better ways to work with proxies? It would be nice not to use Hibernate-specific methods.

You can use polymorphism to handle this instead. Add a method Class<?> getDomainClass() { return getClass(); } to your base class to get the actual class and boolean isInstanceOf(Class<?> clazz) { return clazz.isInstance(this); } to check if an object is a subtype.
When you use these methods instead, Hibernate will initialize lazy proxies and delegate the call to the real object, but you don’t have to use Hibernate specific methods if you really want to avoid that.