Can I "join" two tables to the same class while creating a one-to-one relationship with NHibernate?

We have a legacy database schema that I tried (unsuccessfully) to map to NHibernate. To give a simplified example, let's say I need a Person class whose name comes from the "Person" table, but their last name comes from the "Person2" table. The Person table also has a Car ID, and I want my Person class to have a Car property. I can display all of this 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>

      

Lets me combine Person and Person2 tables, and lets me find them Car - everything works fine.

But ... if there is a person HouseId in the Person2 table, I would like to add a second item to my mapping ...

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

      

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

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

MySql.Data.MySqlClient.MySqlException: # 42S22 Unknown column "HouseId" in "field list"

Is NHibernate capable of doing what I am trying, is there another way to achieve this (without changing the database schema), or have I just made a beginner error in my map file?

+1


a source to share


1 answer


Vincent - thanks for your answer. No. I have not wrapped the tag element inside the element. But following your suggestion, I tried and it works great! Thank you very much for your reply.



<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>

      

+1


a source







All Articles