Primary Identifier Mappings

Primary identifier mapping is mandatory in NHibernate. Primary identifiers of entity classes are mapped to primary keys of master tables in data sources. If not defined, a default primary identifier mapping will be generated, but this may not work properly.

There are three kinds of primary identifier mapping in NHibernate:

Mapped classes must declare the primary key column of the database table. Most classes will also have a property holding the unique identifier of an instance.

Composite Identifier Mapping

If a primary key comprises more than one column, the primary identifier can have multiple attributes mapped to these columns. In some cases, the primary key column could also be the foreign key column.



In the above example, the Assignment class has a primary identifier with three attributes: one basic type attribute and two migrated attributes. The primary identifier mapping is as follows:

<composite-id>
  < key-property name="Type" access="property">
    < column name="Type" sql-type="integer" 
				not-null="true"/>
  </key-property>
  <key-many-to-one name="title" access="property">
  </key-many-to-one>
  <key-many-to-one name="worker" access="property">
  </key-many-to-one>
</composite-id>

Component Primary Identifier Mapping

For more convenience, a composite identifier can be implemented as a separate value type class. The primary identifier has just one attribute with the class type. The separate class should be defined as a value type class. Component class mapping will be generated then.



In the example above, three name attributes are grouped into one separate class Name. It is mapped to the same table as Person class. The generated primary identifier is as follows:

<composite-id name="name" class="identifier.Name">
  <key-property name="firstName">
    <column name="name_firstName"
    sql-type="text"/>
  </key-property>
  <key-property name="middleName">
    <column name="name_middleName" 
    sql-type="text"/>
  </key-property>
  <key-property name="lastName">
    <column name="name_lastName" 
    sql-type="text"/>
  </key-property>
</composite-id>

Note: The value type class must implement the java.io.Serializable interface, which implements the equals() and hashCode() methods.