NHibernate: Mapping Application Domain

Mapping Class Associations

Summary

Associations refer to relationships between entities, and are mainly unidirectional.

One-to-many associations are the most important and popular type.

Many-to-many associations can be represented as two many-to-one associations. To represent a many-to-one relationship, need to definite two associations. One association mapping the many-to-one side of the relationship, and the other mapping representing the one-to-many side of the relationship.

One-to-one association

There are two different ways to represent one-to-one associations:

  • Use a <many-to-one> mapping with a unique constraint on the foreign key. To make this association truly one-to-one, you add unique="true" to the <many-to-one> element. Map the other end of the association, using a <one-to-one> association. An example of use would be when mapping a user instance from a User table to two instances of an address in an Address table.
  • Both ends of the association are mapped using <one-to-one> associations. Use constrained="true" property on one association to indicate a foreign key constraint that refers to the primary key of the other association. Use the <generator class="foreign"> mapping declaration to ensure instances of both associations are assigned the same identifier value. The <param> named property of the foreign generator allows you to name a one-to-one association.

Many-to-many association

Use an intermediate association class to represent a many-to-many relationship.

For unidirectional many-to-many relationships:

  • Use the <many-to-many> association to map the intermediate table, or
  • Use the idbag collection interface, or
  • Use the list or map collections

For bidirectional many-to-many associations:

  • Each row of the intermediate table is represented by two collections, one at each end of the association.
  • Must declare one end of the association using inverse="true" to define which side's state is used to update the intermediate table.
  • Can use a set, idbag, list or map collection for the non-inverse end of the bidirectional association.
  • For the inverse end, use the set collection. Indexed collections such as lists and maps can't be used, because HNibernate won't initialize or maintain the index column if inverse="true".

One-to-many association

Used to map a typical parent/child relationship between two entity persistent classes using a <one-to-many> and a <many-to-one> mapping.

Use a <set> collection mappings for typical parent/child relationships.