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”.
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.