views:

192

answers:

1

Hello. I have the following object model:

  • A top-level abstract class Element with many children and descendants.
  • A class Event.
  • Each Element contains a bag of Events.
  • Each Event has a pointer to the parent Element.

Up till now - pretty standart one-to-many relationship.

But, I want to use table per concrete class strategy. So, the class Element is not mapped to the database. I've tried to solve it this way: each of the concrete descendants of Element defines its own Bag of Events. The problem with this is that each <bag> element contains a <key> element. That key points to the Parent property of Event. It also makes the Parent column in the Events table a foreign key to the table which contains the Bag! But one column can't be a foreign key to several tables and I'm getting an exception on insert.

I've also tried to make the Parent field in the Events table a many-to-any kind of field. That worked. But when I want to make the relation bidirectional, meaning, to add the bags to the descendants of Element I come back to the same problem. Bag => foreign key => exception on insert.

I'm sure this case isn't as unique as it seems. Thank you in advance for your help.

A: 

A little bit late, but I have some advise.

If you are using "table per concrete class", it is as if you would map completely independent tables. So you need separate foreign keys or many-to-any.

many-to-any stores the type name and NH knows to where the foreign key points. But it's impossible to have constraints on such a foreign key.

If you have several bags having items of the same type, make sure they all define different foreign keys:

<class name="A">
  <!-- ... -->
  <bag name="Events">
    <key column="A_FK"/>
    <one-to-many class="Event"/>
   </bag>
</class>

<class name="B">
  <!-- ... -->
  <bag name="Events">
    <key column="B_FK"/>
    <one-to-many class="Event"/>
   </bag>
</class>

You can have foreign key constraints on such a foreign key, but no not-null constraint, because only one of these foreign keys is used.

To really have only one foreign key with all the constraints, you need to map the element to a separate table.

Stefan Steinegger

related questions