I have a question related to the polymorphic queries.
I have a class hierarchy as the following:
Base class Cat
subclass AmericanCat extends Cat
subclass AsianCat extends Cat
I have another class called Master which has one to one relationship with the Cat using the catId foreign key
Hibernate version:
3.1
Name and version of the database you are using:
MS SQL Server 2005[/code]
Mapping documents:
Cat class hierarchy mapping:
Code:
<hibernate-mapping>
<class name="Cat" table="Cat" schema="dbo" catalog="Test2">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="50" not-null="true" />
</property>
<property name="type" type="java.lang.String">
<column name="discriminator" length="50" />
</property>
<joined-subclass name="AmericanCat" table="AmericanCat">
<key column="catId" />
<property name="americanName" type="java.lang.String" column="americanName"/>
</joined-subclass>
<joined-subclass name="AsianCat" table="AsianCat">
<key column="catId" />
<property name="asianPlace" type="java.lang.String" column="asianPlace"/>
</joined-subclass>
</class>
The Master class mapping:
Code:
<class name="Master" table="Master" schema="dbo" catalog="Test">
<id name="masterId" type="java.lang.Integer">
<column name="masterId" />
<generator class="native" >
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="10" not-null="true" />
</property>
<many-to-one name="cat" column="catId" unique="true" not-null="true"/>
</class>
When I perform a query like:
Code:
List masters = session.createQuery("from Master master where master.masterId='1'").list();
Master master = (Master)masters.get(0);
Cat cat = master.getCat();
System.out.println(cat.getId()); // This works fine.
//The following line generates a class cast excpetion although the selected
// cat is indeed of type AmericanCat.
System.out.println( ((AmericanCat)cat).getAmericanName());
I tested the polymorphic query using the "from Cat" and it works perfectly. The returned Cat super class can be casted to its original super class without problems . However, when I select the Master object, the superclass Cat property does not know its original subclass.
Any ideas if I am missing something or if there is any work around ?
Thanks in advance.