views:

30

answers:

2

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

You shouldn't need to specifiy the property as a property in your mapping file when you're also defining a one-to-one relationship for the same value. I haven't used one-to-one, so there may be another issue, but I'd remove the line:

<property name="bID" column="bID" /> 

from tableA and see if that helps.

Kendrick
Didn't make a difference, and I don't know why it would. Both tables have that column, and both mappings should have no problem having those properties.
MonkeyWrench
Worth a shot. I've found some weird side effects from stuff like that, so I thought I'd throw it out there.
Kendrick
+1  A: 

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://nhforge.org/doc/nh/en/index.html#mapping-declaration-onetoone

Diego Mijelshon
Thanks. That worked. Confusing that I have to use a many-to-one element when its really a one-to-one mapping. I also set the fetch type to "join" so reduce the number of queries.
MonkeyWrench
But yes, if you can show a bidirectional example, it would be educational.
MonkeyWrench
There you go...
Diego Mijelshon

related questions