I'm using NHibernate 2.0.1. I have a table per subclass inheritance strategy in which a Student class inherits from a Person class. The PersonID is added to the Student table as a FK and the StudentID is PK.
Furthermore, there is an Enrollment table which records the classes in which a student has enrolled (StudentID is a FK here). Since students can have multiple classes, this is a one to many relationship. Here's the relevant mapping file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ClassRegistration.Domain" namespace="ClassRegistration.Domain" default-lazy="false">
<class name="Person" table="Person">
<id name="PersonID">
<column name="PersonID"/>
<generator class="native" />
</id>
<property name="DtBirth" />
<property name="Address" />
<property name="City" />
<property name="Zip" />
<property name="State" />
<joined-subclass name="ClassRegistration.Domain.Student" table="Student">
<key column="PersonID"/>
<property name="StudentID" generated="insert"/>
<property name="Major/>
<bag name="Enrollments" cascade="all" lazy="true">
<key column="StudentID"/>
<one-to-many class="ClassRegistration.Domain.Enrollment"/>
</bag>
</joined-subclass>
</class>
</hibernate-mapping>
The problem is that NHibernate is using the value for PersonID when joining to fetch the collection of Enrollments instead of the StudentID. In the following SQL, the StudentID is 19, and the PersonID is 4. You'll notice that NHibernate is using the latter instead of the former:
SELECT enrollment0_.StudentID AS StudentID5_ ,
enrollment0_.Enrollmen tID AS Enrollme1_5_ ,
enrollment0_.EnrollmentID AS Enrollme1_7_4_,
enrollment0_.C lassID AS ClassID7_4_ ,
enrollment0_.StudentID AS StudentID7_4_ ,
class1_.ClassID AS ClassID6_0_ ,
class1_.MaxStudents AS MaxStude2_6_0_,
class1_.Day AS Day6_0_ ,
c lass1_.Duration AS Duration6_0_ ,
class1_.BeginTime AS BeginTime6_0_ ,
class1_.Cou rseID AS CourseID6_0_ ,
class1_.LocationID AS LocationID6_0_,
course2_.CourseID a s CourseID1_1_ ,
course2_.Name AS Name1_1_ ,
course2_.Credits AS Credits1_1_ ,
cour se2_.SubjectID AS SubjectID1_1_ ,
course2_.DepartmentID AS Departme5_1_1_ ,
depart ment3_.DepartmentID AS Departme1_5_2_ ,
department3_.Name AS Name5_2_ ,
location4_ .LocationID AS LocationID0_3_ ,
location4_.Building AS Building0_3_ ,
location4_.R oom AS Room0_3_
FROM Enrollment enrollment0_
LEFT OUTER JOIN Class class1_
ON en rollment0_.ClassID=class1_.ClassID
LEFT OUTER JOIN Course course2_
ON class1_.Co urseID=course2_.CourseID
LEFT OUTER JOIN Department department3_
ON course2_.Dep artmentID=department3_.DepartmentID
LEFT OUTER JOIN Location location4_
ON class 1_.LocationID=location4_.LocationID
WHERE enrollment0_.StudentID =@p0; @p0=4
|