R – “join” two tables into one class whilst also creating many-to-one relationships using NHibernate

nhibernate

We have a legacy database schema which I've tried (unsuccessfully) to map with NHibernate. To give a simplified example, say I want a Person class whose first name comes from the "Person" table, but their last name comes from the "Person2" table. The "Person" table also has the Id of the person's Car and I want my Person class to have a Car property. I can map all that using the following;

<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
  <class name="NHibernateMappingTest.Person, NHibernateMappingTest" lazy="false">
    <id name="Id" >
      <generator class="native" />
    </id>
    <property name="FirstName" />
    <many-to-one name="Car" access="property" class="NHibernateMappingTest.Car, NHibernateMappingTest" column="CarId"  cascade="save-update"/>
    <join table="Person2">
      <key column="PersonId" />
      <property name="LastName" />
    </join>
  </class>
</hibernate-mapping>

The lets me combine the Person and Person2 tables, and the lets me find their Car – everything works fine.

But… if the Person2 table happens to have the person's HouseId, I'd like to be able to add a second element to my mapping…

<many-to-one name="House" access="property" class="NHibernateMappingTest.House, NHibernateMappingTest" column="HouseId" cascade="save-update"/>

…so that my Person class can have a House property.

However this is where it all goes wrong, because the SQL which NHibernate generates assumes that the HouseId column is in the Person table (but it's not, it's in Person2), so I get the following error;

MySql.Data.MySqlClient.MySqlException: #42S22Unknown column 'HouseId' in 'field list'

Is NHibernate able to do what I'm attempting, is there a different way to achieve this (without changing the database schema), or have I just made a beginner's error in my map file?

Best Answer

Vincent - thanks for your response. No I wasn't nesting the tag element inside the element. But following your suggestion, I tried and it works perfectly! Thanks very much for responding.

<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
      <class name="NHibernateMappingTest.Person, NHibernateMappingTest" lazy="false">
        <id name="Id" >
          <generator class="native" />
        </id>
        <property name="FirstName" />
        <many-to-one name="Car" access="property" class="NHibernateMappingTest.Car, NHibernateMappingTest" column="CarId"  cascade="save-update"/>
        <join table="Person2">
          <key column="PersonId" />
          <property name="LastName" />
          <many-to-one name="House" access="property" class="NHibernateMappingTest.House, NHibernateMappingTest" column="HouseId" cascade="save-update"/>
        </join>
      </class>
    </hibernate-mapping>
Related Topic