ClassCast for similar objects
Hibernate version: 3.2.0 CR4 with Annotationen
DB: MySQL
I hava the following class hirarchie (using Table per subclass strategie):
MethaBean extends Object
Person extends Metha Bean
Employee extends Person
User extends Person
Depending on the context the same person can be a User or an Employee. how to do the cast?
The following code prints always an employee, because I created it as an employee. but how can I convert (cast) it to an User or a Person.
(The second object gets a ClasCastException, of course)
Code:
Session session = SessionFactory.currentSession();
Long lID = new Long(1030);
Object bean1 = null;
Object bean2 = null;
Object bean3 = null;
try
{
bean1 = (Person)session.get(Person.class, lID);
bean3 = (Employee) session.get(Employee.class, lID);
bean2 = (User) session.get(User.class, lID);
}
catch (ClassCastException e)
{
e.printStackTrace();
}
System.out.println("1 Person :" + bean1);
System.out.println("2 User :" + bean2);
System.out.println("3 Employee :" + bean3);
Results:
Code:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
[2006.09.21][com.co.util.hibernate.SessionFactory][][DEBUG]: hibernate SessionFactory created by
[2006.09.21][com.co.util.hibernate.SessionFactory][][DEBUG]: hibernate session opened by
java.lang.ClassCastException: com.co.util.beans.Employee
at com.co.test.HibernateTest.main(HibernateTest.java:39)
1 Person :co.util.beans.Employee: Wasle Florian (1030)
2 User :null
3 Employee :co.util.beans.Employee: Wasle Florian (1030)
Thanks,
Florian