This is by design. Proxies are only designed to support polymorphic access. Contrary to an unfortunately too widespread misconception, casting to a sub type is not polymorphism. The polymorphic approach would be a Flder.unwrap(Class) method. Just realize that calling unwrap would force initialization of the proxy (if not already). When you define the type of a proxy as the super Hibernate simply cannot know the specific subclass the proxy actually point to. This is true whether you are talking about a "root proxy"
Folder f = session.load( Folder.class, id );
( (FolderEx) f ).getDescription();
or you are talking about a proxy via association (which is the use case you are describing). In order to determine that, Hibernate would actually need to load that association eagerly, which is obviously at odds with the entire idea of proxies and lazy loading obviously. Now as an "improvement" Hibernate could conceivably define the proxy for an entity to be castable to all of the entity's subtypes. But I'd argue strongly that that would actually be the opposite of an improvement. I'd find the following code extremely surprising:
Folder f = session.load( Folder.class, id );
if ( f instanceof AnotherFolderSubtype ) {
handleAnotherFolderSubtype( (AnotherFolderSubtype) f );
}
else if (...) {
}
So handle this via polymorphism. That just so happens to be better OO anyway; so rejecting |