Thread:
 another approach to polymorphism in hibernate 
 sebster   28 Mar 2006, 08:05 

Comment
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
From: sebster (28 Mar 2006, 08:05) Replies: 0, Views: 25189
Subject: another approach to polymorphism in hibernate
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
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]