I'm running into a problem with polymorphic objects. I'll explain my current situation:
- I have a base class called Person
- I have a class called Student which inherits from Person
- I have a class called Teacher which inherits from Person
I have a table for every class, all the base data is stored in the Person's class and table (Firstname, Lastname, etc.). I also have a Student table with a primary key PersonID (which links to the Person table). The Teacher table also has a primary key called PersonID, which also links to the Person table).
Below is the mapping:
Code:
<class name="Person" table="Persons" lazy="false">
<!-- Identity mapping -->
<id name="ID" unsaved-value="0">
<column name="ID" />
<generator class="identity" />
</id>
<!-- Simple mappings -->
<property name="Initials" />
<property name="FirstName" />
<property name="MiddleName" />
<property name="LastName" />
<property name="Gender" />
<property name="DateOfBirth" type="date" />
<property name="Street" />
<property name="HouseNumber" />
<property name="HouseNumberExtension" />
<property name="ZipCode" />
<property name="City" />
<property name="Phone" />
<property name="CellPhone" />
<property name="Email" />
<property name="CreatedOn" />
<property name="IsStudent" formula="(SELECT (CASE WHEN (COUNT(*) = 0) THEN 0 ELSE 1 END) FROM Students WHERE Students.PersonID=ID)"/>
<property name="IsTeacher" formula="(SELECT (CASE WHEN (COUNT(*) = 0) THEN 0 ELSE 1 END) FROM Teachers WHERE Teachers.PersonID=ID)"/>
<joined-subclass name="Student" table="Students" lazy="false">
<key column="PersonID" />
<joined-subclass name="Teacher" table="Teachers" lazy="false">
<key column="PersonID" />
</class>
When I call the method List<Person>() on the IQuery interface, it throws the exception:
Code:
Object with id: 2 was not of the specified subclass: Teacher (loading object was of wrong class Student)
The weird part is that when I call the method List<Student>() on the IQuery interface, it doesn't throw any exception. It loads all the data correctly. I can't call List<Teacher>() and I can't call List<Person>() either...
Can someone please give me a clue where to look at? I've tried using HQL but it didn't work either (0 results).
Code:
from Person p where p.class = Person
If I change it to:
Code:
from Person
It throws the same exception as mentioned earlier.