When tried to tune our near-production application, we came to problem when a single entity reference (not a collection) is loaded lazily. We used inheritance with this entity and hibernate JPA provider (as probably any other provider) inserts a proxy object into referencing entity instead of reference to real object loaded from database (as it is not yet loaded).
We came to a problem because we were casting super class to subclasses using instanceof. The problem is that proxy class is already a subclass and cannot be cast to a sibling class. It is a proxy only to super class instance, but it's not possible to access methods of superclasses directly. The proxy never gets converted to real subclass. The problem is specified here, here and here. All described solutions depend on hibernate non-standard API to retrieve deproxied instance.
However, after lots of thinking...
... I found a solution to deproxy a class using standard Java and JPA API. Tested with hibernate, but does not require hibernate as a dependency and should work with all JPA providers.
Only one requirement - its necessary to modify parent class (Address) and add a simple helper method.
General idea: add helper method to parent class which returns itself. when method called on proxy, it will forward the call to real instance and return this real instance.
Implementation is a little bit more complex, as hibernate recognizes that proxied class returns itself and still returns proxy instead of real instance. Workaround is to wrap returned instance into a simple wrapper class, which has different class type than the real instance.
In code:
class Address {
public AddressWrapper getWrappedSelf() {
return new EntityWrapper(this);
}
...
}
class AddressWrapped {
private Address wrappedAddress;
...
}
To cast Address proxy to real subclass, use following:
Address address = dao.getSomeAddress(...);
Address deproxiedAddress = address.getWrappedSelf().getWrappedAddress();
if (deproxiedAddress instanceof WorkAddress) {
WorkAddress workAddress = (WorkAddress)deproxiedAddress;
}
Brilliant in its simplicity! Thanks a lot, I had to face the same issue and you helped a lot.
ReplyDeleteI'm happy to see that even a 3 year old post can help others :) Thanks for letting me know!
ReplyDelete