Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate one-to-one mapping, non-primary keys

Can't get NHibernate to generate the correct query. It keeps using the primary keys of the two tables I'm joining for the one-to-one relationship, and I can't figure out how to specify the foreign key in one of the tables.

tableA      tableB
{ aID,      { bID,
  bID,        z,
  c,          y,
  d }         x }

so the tableA should join to tableB using tableA.bID = tableB.bID. How can I specify this in the mapping for tableA? I'm using the tableA class to retrieve a row from tableA and a row from tableB, as it is a real one to one relationship.

NHibernate generates the sql to join the tables using tableA.aID = tableB.bID, which is wrong.

This does not work:

<class name="tableA" table="tableA">
  <id name="aID" column="aID" />
  <property name="bID" column="bID" />
  <property name="c" column="c" />
  <property name="d" column="d" />
  <one-to-one name="otherThing" class="tableB" foreign-key="bID" />
</class>

<class name="tableB" table="tableB">
  <id name="bID" column="bID" />
  <property name="z" column="z" />
  <property name="y" column="y" />
  <property name="x" column="x" />
</class>
like image 407
MonkeyWrench Avatar asked Oct 06 '10 14:10

MonkeyWrench


1 Answers

This is the correct way to map it:

<class name="tableA" table="tableA">
  ...
  <many-to-one name="otherThing" class="tableB" column="bID" unique="true" />
</class>
  • I'm assuming this is really one-to-one, hence the unique.
  • You should map each column ONCE. If it's a relationship, then it's not an int property.

A reference from tableB to tableA would be implemented as:

<class name="tableB" table="tableB">
  ...
  <one-to-one name="A" class="tableA" property-ref="otherThing" />
</class>

This is all documented in http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-onetoone

like image 109
Diego Mijelshon Avatar answered Nov 15 '22 21:11

Diego Mijelshon