views:

325

answers:

1

I have two tables, Vehicle and Make. The two are joined using the MakeId as a foreign key on the Vehicle table. My mapping file looks similar to this

    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping  xmlns="urn:nhibernate-mapping-2.2">
      <class name="Demo.Business.Objects.Vehicle, Demo.Business.Objects" table="Vehicle" >
        <id name="VehicleId" type="int" >
          <generator class="native"  />
        </id>
        <property name="RegNumber" type="String" />
        <property name="VehicleId" type="int" />
        <property name="CustomerId" type="int" />

        <join table="Make"  fetch="join">

          <key column="MakeId" foreign-key="MakeId"/>
          <property name="Description"  type="String"  />
        </join>
      </class>
    </hibernate-mapping>

I would have thought that this would join the two tables on the make id, however the SQL that ios generated tries the following join: vehicle.vehicleid = make.makeid.

How can I get this to work? I.e. I expect:

    select * from Vehicle
    inner join Make on Make.MakeId = Vehicle.Make Id
A: 

You need to map the Make class differently:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping  xmlns="urn:nhibernate-mapping-2.2">
  <class name="Demo.Business.Objects.Vehicle, Demo.Business.Objects" table="Vehicle" >
    <id name="VehicleId" type="int" >
      <generator class="native"  />
    </id>
    <property name="RegNumber" type="String" />
    <property name="VehicleId" type="int" />
    <property name="CustomerId" type="int" />
    <many-to-one name="Make" column="MakeId"/>
  </class>
  <class name="(blahblah).Make, blahblah">
    <id name="MakeId" type="int">
      <generator class="native" />
    </id>

    <property name="Description"  type="String"  />
  </class>
</hibernate-mapping>

Your "Vehicle" class should have a Make property of type Make.

Jan Willem B
I've had it working like this already. This gives the Vehicle a property of the Make objesct (unfortunatly, the Make table is also joined to other tables with foreign keys and I don't want a horrendously deep object graph). I can't change the schema of the db as the client needs to support legacy applications. Therefore what I want to achieve is is more like a "view" whereby all of the appropriate columns from the joined tables are retrieved. This would work much like an aggregate table in EF.
januszstabik
nhibernate many-to-one relations are lazy by default, so the object graph won't be fetched unless you specify otherwise.
Jan Willem B
I can get around the loading issue, thats fine. The schema of the DB is very normalized meaning that my object graph in places might be 5-6 objects deep, further meaning that were going to be using syntax like object1.object2.object3.object4.object5.object6.Name. I'm not sure the client is going to like this so wanted to find a solution before I said it couldn't be done.
januszstabik