views:

106

answers:

3

We have three tables A, B, C.

Columns

A => id, x

B => id, y

C => A.id, B.id

For every row in A there will be a row in B. To relate A and B we are using C (we cannot change the table design). We have to persist information in one transaction. Is there a way to do it using NHibernate?

A: 

Never had to do this myself, but you may want to look at using some joined-table mappings.

And for transactional operations, simply:

using(var session = TheSessionFactory.OpenSession()) {
    using(var txn = session.BeginTransaction()) {
        //transactional work
        txn.Commit();
    }
}
Justice
A: 

It depends on what your class structure is or what you're looking for in a class structure. If those are really the only columns in the tables then this way seems overkill and make for some less than optimal ways for accessing X & Y (classC.A.X & classC.B.X) but it would work. Maybe you could have some non-saved properties on ClassC that made those calls for you in a more succinct manner.

<class name="ClassA" table="A">
   <id name="Id" column="ID">
      <generator class="native"/>
   </id>
   <property name="x" column="X" />
</class>

<class name="ClassB" table="B">
   <id name="Id" column="ID">
      <generator class="native"/>
   </id>
   <property name="y" column="Y" />
</class>

<class name="ClassC" table="C">
   <id name="Id" column="ID">
      <generator class="native"/>
   </id>
   <many-to-one name="A" class="ClassA" column="A_ID"/>
   <many-to-one name="B" class="ClassB" column="B_ID"/>
</class>

If C only has those columns, you could change this to use a composite id (look to the docs). Then, also depending on your wants, you could setup the cascading so you only ever messed with ClassC as far as CRUD went.

Mark G
A: 

What you are describing here is a many-to-many table mapping. there is a many-to-many mapping property. this means that you will not need a mapping for table C.

To borrow the Mapping from Mark G's Answer.

<class name="ClassA" table="A">
   <id name="Id" column="ID">
      <generator class="native"/>
   </id>
   <property name="x" column="X" />
   <bag name="List_Of_B" table="C" cascade="all">
      <key column="AId"/>
      <many-to-many column="BId"
         class="B"/>
   </bag>
</class>

<class name="ClassB" table="B">
   <id name="Id" column="ID">
      <generator class="native"/>
   </id>
   <property name="y" column="Y" />
   <bag name="List_Of_A" table="C" cascade="all">
      <key column="BId"/>
      <many-to-many column="AId"
         class="A"/>
   </bag>
</class>
Nathan Fisher