POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE
PAGE!I have a different solution which also works (and also has its
drawbacks). What I did is to let the base class (Politician) have two
methods:
public boolean instanceOf(Class<?> otherClass) {
return otherClass.isAssignableFrom(getPoliticianClass());
}
public Class<?> getPoliticianClass() {
return Politician.class;
}
Next I override the getPoliticianClass() for the Democrat as follows:
public Class<?> getPoliticianClass() {
return Democrat.class;
}
Now you can do the following in your code:
Politician politician = ...; // code to find your (s)elected politician
if (politician.instanceOf(Democrat.class) {
// politician is a democrat
Democrat democrat = (Democrat) session.get(Democrat.class,
politician.getId())
// Use your democrat.
}
Note that regetting your instance from the session narrows the proxy to
the Democrat class and breaks ==, i.e., in the above code democrat ==
politician returns false. However you DO still have a proxy around your
democrat (which does lazy loading etc), which doesn't seem to be the
case if you implement the above visitor pattern.
I would really like hibernate to just make a proxy for the narrowest
entity class for each entity it loads to begin with, then == works again
and so do regular instanceof checks and typecasts. However I don't know
the technical details why hibernate does not do this... (perfomance?).
Regards,
Sebastiaan |