Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate mapping one table on two classes with where selection

We would like to map a single table on two classes with NHibernate. The mapping has to be dynamically depending on the value of a column.

Here's a simple example to make it a bit clearer: We have a table called Person with the columns id, Name and Sex.

alt text

The data from this table should be mapped either on the class Male or on the class Female depending on the value of the column Sex.

alt text

In Pseudocode:

create instance of Male with data from table Person where Person.Sex = 'm';
create instance of Female with data from table Person where Person.Sex = 'f'; 

The benefit is we have strongly typed domain models and can later avoid switch statements.

Is this possible with NHibernate or do we have to map the Person table into a flat Person class first? Then afterwards we would have to use a custom factory method that takes a flat Person instance and returns a Female or Male instance. Would be good if NHibernate (or another library) can handle this.

like image 709
Rene Schulte Avatar asked Jun 03 '10 09:06

Rene Schulte


1 Answers

This is quite a common case for NHibernate. You can map whole class hierarchies into a single table.

You need to specify a discriminator value.

<class name="Person">
  <id .../>

  <discriminator column="Sex" type="string" length="1" />

  <property name="Name"/>
  <!-- add more Person-specific properties here -->

  <subclass name="Male" discriminator-value="m">
    <!-- You could add Male-specific properties here. They 
     will be in the same table as well. Or just leave it empty. -->
  </subclass>

  <subclass name="Female" discriminator-value="f">
    <!-- You could add Female-specific properties here. They 
     will be in the same table as well. Or just leave it empty. -->
  </subclass>

</class>
like image 169
Stefan Steinegger Avatar answered Sep 28 '22 09:09

Stefan Steinegger