Chapter 5. Basic O/R Mapping

5.1. Mapping declaration

Object/relational mappings are defined in an XML document. The mapping document is designed to be readable and hand-editable. The mapping language is object-centric, meaning that mappings are constructed around persistent class declarations, not table declarations.

Note that, even though many NHibernate users choose to define XML mappings by hand, a number of tools exist to generate the mapping document, including NHibernate.Mapping.Attributes library and various template-based code generators (CodeSmith, MyGeneration).

Let's kick off with an example mapping:

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Eg"
    namespace="Eg">

        <class name="Cat" table="CATS" discriminator-value="C">
                <id name="Id" column="uid" type="Int64">
                        <generator class="hilo"/>
                </id>
                <discriminator column="subclass" type="Char"/>
                <property name="BirthDate" type="Date"/>
                <property name="Color" not-null="true"/>
                <property name="Sex" not-null="true" update="false"/>
                <property name="Weight"/>
                <many-to-one name="Mate" column="mate_id"/>
                <set name="Kittens">
                        <key column="mother_id"/>
                        <one-to-many class="Cat"/>
                </set>
                <subclass name="DomesticCat" discriminator-value="D">
                        <property name="Name" type="String"/>
                </subclass>
        </class>

        <class name="Dog">
                <!-- mapping for Dog could go here -->
        </class>

</hibernate-mapping>

We will now discuss the content of the mapping document. We will only describe the document elements and attributes that are used by NHibernate at runtime. The mapping document also contains some extra optional attributes and elements that affect the database schemas exported by the schema export tool. (For example the not-null attribute.)

5.1.1. XML Namespace

All XML mappings should declare the XML namespace shown. The actual schema definition may be found in the src\nhibernate-mapping.xsd file in the NHibernate distribution.

Tip: to enable IntelliSense for mapping and configuration files, copy the appropriate .xsd files to <VS.NET installation directory>\Common7\Packages\schemas\xml.

5.1.2. hibernate-mapping

This element has several optional attributes. The schema attribute specifies that tables referred to by this mapping belong to the named schema. If specified, tablenames will be qualified by the given schema name. If missing, tablenames will be unqualified. The default-cascade attribute specifies what cascade style should be assumed for properties and collections which do not specify a cascade attribute. The auto-import attribute lets us use unqualified class names in the query language, by default. The assembly and namespace attributes specify the assembly where persistent classes are located and the namespace they are declared in.

<hibernate-mapping
         schema="schemaName"                          (1)
         default-cascade="none|save-update"           (2)
         auto-import="true|false"                     (3)
         assembly="Eg"                                (4)
         namespace="Eg"                               (5)
 />
(1)

schema (optional): The name of a database schema.

(2)

default-cascade (optional - defaults to none): A default cascade style.

(3)

auto-import (optional - defaults to true): Specifies whether we can use unqualified class names (of classes in this mapping) in the query language.

(4)(5)

assembly and namespace(optional): Specify assembly and namespace to assume for unqualified class names in the mapping document.

If you are not using assembly and namespace attributes, you have to specify fully-qualified class names, including the name of the assembly that classes are declared in.

If you have two persistent classes with the same (unqualified) name, you should set auto-import="false". NHibernate will throw an exception if you attempt to assign two classes to the same "imported" name.

5.1.3. class

You may declare a persistent class using the class element:

<class
        name="ClassName"                              (1)
        table="tableName"                             (2)
        discriminator-value="discriminator_value"     (3)
        mutable="true|false"                          (4)
        schema="owner"                                (5)
        proxy="ProxyInterface"                        (6)
        dynamic-update="true|false"                   (7)
        dynamic-insert="true|false"                   (8)
        select-before-update="true|false"             (9)
        polymorphism="implicit|explicit"              (10)
        where="arbitrary sql where condition"         (11)
        persister="PersisterClass"                    (12)
        batch-size="N"                                (13)
        optimistic-lock="none|version|dirty|all"      (14)
        lazy="true|false"                             (15)
/>
(1)

name: The fully qualified .NET class name of the persistent class (or interface), including its assembly name.

(2)

table: The name of its database table.

(3)

discriminator-value (optional - defaults to the class name): A value that distiguishes individual subclasses, used for polymorphic behaviour. Acceptable values include null and not null.

(4)

mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.

(5)

schema (optional): Override the schema name specified by the root <hibernate-mapping> element.

(6)

proxy (optional): Specifies an interface to use for lazy initializing proxies. You may specify the name of the class itself.

(7)

dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed.

(8)

dynamic-insert (optional, defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

(9)

select-before-update (optional, defaults to false): Specifies that NHibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. In certain cases (actually, only when a transient object has been associated with a new session using update()), this means that NHibernate will perform an extra SQL SELECT to determine if an UPDATE is actually required.

(10)

polymorphism (optional, defaults to implicit): Determines whether implicit or explicit query polymorphism is used.

(11)

where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving objects of this class

(12)

persister (optional): Specifies a custom IClassPersister.

(13)

batch-size (optional, defaults to 1) specify a "batch size" for fetching instances of this class by identifier.

(14)

optimistic-lock (optional, defaults to version): Determines the optimistic locking strategy.

(15)

lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".

It is perfectly acceptable for the named persistent class to be an interface. You would then declare implementing classes of that interface using the <subclass> element. You may persist any inner class. You should specify the class name using the standard form ie. Eg.Foo+Bar, Eg. Due to an HQL parser limitation inner classes can not be used in queries in NHibernate 1.0.

Immutable classes, mutable="false", may not be updated or deleted by the application. This allows NHibernate to make some minor performance optimizations.

The optional proxy attribute enables lazy initialization of persistent instances of the class. NHibernate will initially return proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. See "Proxies for Lazy Initialization" below.

Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or the class and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphism means that class instances will be returned only be queries that explicitly name that class and that queries that name the class will return only instances of subclasses mapped inside this <class> declaration as a <subclass> or <joined-subclass>. For most purposes the default, polymorphism="implicit", is appropriate. Explicit polymorphism is useful when two different classes are mapped to the same table (this allows a "lightweight" class that contains a subset of the table columns).

The persister attribute lets you customize the persistence strategy used for the class. You may, for example, specify your own subclass of NHibernate.Persister.EntityPersister or you might even provide a completely new implementation of the interface NHibernate.Persister.IClassPersister that implements persistence via, for example, stored procedure calls, serialization to flat files or LDAP. See NHibernate.DomainModel.CustomPersister for a simple example (of "persistence" to a Hashtable).

Note that the dynamic-update and dynamic-insert settings are not inherited by subclasses and so may also be specified on the <subclass> or <joined-subclass> elements. These settings may increase performance in some cases, but might actually decrease performance in others. Use judiciously.

Use of select-before-update will usually decrease performance. It is very useful to prevent a database update trigger being called unnecessarily.

If you enable dynamic-update, you will have a choice of optimistic locking strategies:

  • version check the version/timestamp columns

  • all check all columns

  • dirty check the changed columns

  • none do not use optimistic locking

We very strongly recommend that you use version/timestamp columns for optimistic locking with NHibernate. This is the optimal strategy with respect to performance and is the only strategy that correctly handles modifications made outside of the session (ie. when ISession.Update() is used). Keep in mind that a version or timestamp property should never be null, no matter what unsaved-value strategy, or an instance will be detected as transient.

Beginning with NHibernate 1.2.0, version numbers start with 1, not 0 as in previous versions. This was done to allow using 0 as unsaved-value for the version property.

5.1.4. id

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. The <id> element defines the mapping from that property to the primary key column.

<id
        name="PropertyName"                      (1)
        type="typename"                          (2)
        column="column_name"                     (3)
        unsaved-value="any|none|null|id_value"   (4)
        access="field|property|nosetter|ClassName(5)">

        <generator class="generatorClass"/>
</id>
(1)

name (optional): The name of the identifier property.

(2)

type (optional): A name that indicates the NHibernate type.

(3)

column (optional - defaults to the property name): The name of the primary key column.

(4)

unsaved-value (optional - defaults to a "sensible" value): An identifier property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session.

(5)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

If the name attribute is missing, it is assumed that the class has no identifier property.

The unsaved-value attribute is almost never needed in NHibernate 1.0.

There is an alternative <composite-id> declaration to allow access to legacy data with composite keys. We strongly discourage its use for anything else.

5.1.4.1. generator

The required <generator> child element names a .NET class used to generate unique identifiers for instances of the persistent class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element.

<id name="Id" type="Int64" column="uid" unsaved-value="0">
        <generator class="NHibernate.Id.TableHiLoGenerator">
                <param name="table">uid_table</param>
                <param name="column">next_hi_value_column</param>
        </generator>
</id>

All generators implement the interface NHibernate.Id.IIdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, NHibernate provides a range of built-in implementations. There are shortcut names for the built-in generators:

increment

generates identifiers of any integral type that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server and Sybase. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported.

sequence

uses a sequence in DB2, PostgreSQL, Oracle or a generator in Firebird. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported.

hilo

uses a hi/lo algorithm to efficiently generate identifiers of any integral type, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with a user-supplied connection.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of any integral type, given a named database sequence.

uuid.hex

uses System.Guid and its ToString(string format) method to generate identifiers of type string. The length of the string returned depends on the configured format.

uuid.string

uses a new System.Guid to create a byte[] that is converted to a string.

guid

uses a new System.Guid as the identifier.

guid.comb

uses the algorithm to generate a new System.Guid described by Jimmy Nilsson in the article http://www.informit.com/articles/article.asp?p=25862.

native

picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before Save() is called.

foreign

uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

5.1.4.2. Hi/Lo Algorithm

The hilo and seqhilo generators provide two alternate implementations of the hi/lo algorithm, a favorite approach to identifier generation. The first implementation requires a "special" database table to hold the next available "hi" value. The second uses an Oracle-style sequence (where supported).

<id name="Id" type="Int64" column="cat_id">
        <generator class="hilo">
                <param name="table">hi_value</param>
                <param name="column">next_value</param>
                <param name="max_lo">100</param>
        </generator>
</id>
<id name="Id" type="Int64" column="cat_id">
        <generator class="seqhilo">
                <param name="sequence">hi_value</param>
                <param name="max_lo">100</param>
        </generator>
</id>

Unfortunately, you can't use hilo when supplying your own IDbConnection to NHibernate. NHibernate must be able to fetch the "hi" value in a new transaction.

5.1.4.3. UUID Hex Algorithm

<id name="Id" type="String" column="cat_id">
        <generator class="uuid.hex">
            <param name="format">format_value</param>
            <param name="seperator">seperator_value</param>
        </generator>
</id>

The UUID is generated by calling Guid.NewGuid().ToString(format). The valid values for format are described in the MSDN documentation. The default seperator is - and should rarely be modified. The format determines if the configured seperator can replace the default seperator used by the format.

5.1.4.4. UUID String Algorithm

The UUID is generated by calling Guid.NewGuid().ToByteArray() and then converting the byte[] into a char[]. The char[] is returned as a String consisting of 16 characters.

5.1.4.5. GUID Algorithms

The guid identifier is generated by calling Guid.NewGuid(). To address some of the performance concerns with using Guids as primary keys, foreign keys, and as part of indexes with MS SQL the guid.comb can be used. The benefit of using the guid.comb with other databases that support GUIDs has not been measured.

5.1.4.6. Identity columns and Sequences

For databases which support identity columns (DB2, MySQL, Sybase, MS SQL), you may use identity key generation. For databases that support sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, SAP DB) you may use sequence style key generation. Both these strategies require two SQL queries to insert a new object.

<id name="Id" type="Int64" column="uid">
        <generator class="sequence">
                <param name="sequence">uid_sequence</param>
        </generator>
</id>
<id name="Id" type="Int64" column="uid" unsaved-value="0">
        <generator class="identity"/>
</id>

For cross-platform development, the native strategy will choose from the identity, sequence and hilo strategies, dependent upon the capabilities of the underlying database.

5.1.4.7. Assigned Identifiers

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).

Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

5.1.5. composite-id

<composite-id
        name="PropertyName"
        class="ClassName"
        unsaved-value="any|none"
        access="field|property|nosetter|ClassName">

        <key-property name="PropertyName" type="typename" column="column_name"/>
        <key-many-to-one name="PropertyName class="ClassName" column="column_name"/>
        ......
</composite-id>

For a table with a composite key, you may map multiple properties of the class as identifier properties. The <composite-id> element accepts <key-property> property mappings and <key-many-to-one> mappings as child elements.

<composite-id>
        <key-property name="MedicareNumber"/>
        <key-property name="Dependent"/>
</composite-id>

Your persistent class must override Equals() and GetHashCode() to implement composite identifier equality. It must also be Serializable.

Unfortunately, this approach to composite identifiers means that a persistent object is its own identifier. There is no convenient "handle" other than the object itself. You must instantiate an instance of the persistent class itself and populate its identifier properties before you can load() the persistent state associated with a composite key. We will describe a much more convenient approach where the composite identifier is implemented as a seperate class in Section 7.4, “Components as composite identifiers”. The attributes described below apply only to this alternative approach:

  • name (optional, required for this approach): A property of component type that holds the composite identifier (see next section).

  • access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

  • class (optional - defaults to the property type determined by reflection): The component class used as a composite identifier (see next section).

5.1.6. discriminator

The <discriminator> element is required for polymorphic persistence using the table-per-class-hierarchy mapping strategy and declares a discriminator column of the table. The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. A restricted set of types may be used: String, Char, Int32, Byte, Short, Boolean, YesNo, TrueFalse.

<discriminator
        column="discriminator_column"  (1)
        type="discriminator_type"      (2)
        force="true|false"             (3)
        insert="true|false"            (4)
        formula="arbitrary SQL expressi(5)on"
/>
(1)

column (optional - defaults to class) the name of the discriminator column.

(2)

type (optional - defaults to String) a name that indicates the NHibernate type

(3)

force (optional - defaults to false) "force" NHibernate to specify allowed discriminator values even when retrieving all instances of the root class.

(4)

insert (optional - defaults to true) set this to false if your discriminator column is also part of a mapped composite identifier.

(5)

formula (optional) an arbitrary SQL expression that is executed when a type has to be evaluated. Allows content-based discrimination.

Actual values of the discriminator column are specified by the discriminator-value attribute of the <class> and <subclass> elements.

The force attribute is (only) useful if the table contains rows with "extra" discriminator values that are not mapped to a persistent class. This will not usually be the case.

Using the formula attribute you can declare an arbitrary SQL expression that will be used to evaluate the type of a row:

<discriminator
    formula="case when CLASS_TYPE in ('a', 'b', 'c') then 0 else 1 end"
    type="Int32"/>

5.1.7. version (optional)

The <version> element is optional and indicates that the table contains versioned data. This is particularly useful if you plan to use long transactions (see below).

<version
        column="version_column"                            (1)
        name="PropertyName"                                (2)
        type="typename"                                    (3)
        access="field|property|nosetter|ClassName"         (4)
        unsaved-value="null|negative|undefined|value"      (5)
/>
(1)

column (optional - defaults to the property name): The name of the column holding the version number.

(2)

name: The name of a property of the persistent class.

(3)

type (optional - defaults to Int32): The type of the version number.

(4)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(5)

unsaved-value (optional - defaults to a "sensible" value): A version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session. (undefined specifies that the identifier property value should be used.)

Version numbers may be of type Int64, Int32, Int16, Ticks, Timestamp, or TimeSpan (or their nullable counterparts in .NET 2.0).

5.1.8. timestamp (optional)

The optional <timestamp> element indicates that the table contains timestamped data. This is intended as an alternative to versioning. Timestamps are by nature a less safe implementation of optimistic locking. However, sometimes the application might use the timestamps in other ways.

<timestamp
        column="timestamp_column"           (1)
        name="PropertyName"                 (2)
        access="field|property|nosetter|Clas(3)sName"
        unsaved-value="null|undefined|value"(4)
/>
(1)

column (optional - defaults to the property name): The name of a column holding the timestamp.

(2)

name: The name of a property of .NET type DateTime of the persistent class.

(3)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(4)

unsaved-value (optional - defaults to null): A timestamp property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session. (undefined specifies that the identifier property value should be used.)

Note that <timestamp> is equivalent to <version type="timestamp">.

5.1.9. property

The <property> element declares a persistent property of the class.

<property
        name="propertyName"                 (1)
        column="column_name"                (2)
        type="typename"                     (3)
        update="true|false"                 (4)
        insert="true|false"                 (4)
        formula="arbitrary SQL expression"  (5)
        access="field|property|ClassName"   (6)
        optimistic-lock="true|false"        (7)
/>
(1)

name: the name of the property of your class.

(2)

column (optional - defaults to the property name): the name of the mapped database table column.

(3)

type (optional): a name that indicates the NHibernate type.

(4)

update, insert (optional - defaults to true) : specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" property whose value is initialized from some other property that maps to the same column(s) or by a trigger or other application.

(5)

formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have a column mapping of their own.

(6)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(7)

optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, determines if a version increment should occur when this property is dirty.

typename could be:

  1. The name of a NHibernate basic type (eg. Int32, String, Char, DateTime, Timestamp, Single, Byte[], Object, ...).

  2. The name of a .NET type with a default basic type (eg. System.Int16, System.Single, System.Char, System.String, System.DateTime, System.Byte[], ...).

  3. The name of an enumeration type (eg. Eg.Color, Eg).

  4. The name of a serializable .NET type.

  5. The class name of a custom type (eg. Illflow.Type.MyCustomType).

Note that you have to specify full assembly-qualified names for all except basic NHibernate types (unless you set assembly and/or namespace attributes of the <hibernate-mapping> element).

NHibernate supports .NET 2.0 Nullable types. These types are mostly treated the same as plain non-Nullable types internally. For example, a property of type Nullable<Int32> can be mapped using type="Int32" or type="System.Int32".

If you do not specify a type, NHibernate will use reflection upon the named property to take a guess at the correct NHibernate type. NHibernate will try to interpret the name of the return class of the property getter using rules 2, 3, 4 in that order. However, this is not always enough. In certain cases you will still need the type attribute. (For example, to distinguish between NHibernateUtil.DateTime and NHibernateUtil.Timestamp, or to specify a custom type.)

The access attribute lets you control how NHibernate will access the value of the property at runtime. The value of the access attribute should be text formatted as access-strategy.naming-strategy. The .naming-strategy is not always required.

Table 5.1. Access Strategies

Access Strategy NameDescription
property

The default implementation. NHibernate uses the get/set accessors of the property. No naming strategy should be used with this access strategy because the value of the name attribute is the name of the property.

field

NHibernate will access the field directly. NHibernate uses the value of the name attribute as the name of the field. This can be used when a property's getter and setter contain extra actions that you don't want to occur when NHibernate is populating or reading the object. If you want the name of the property and not the field to be what the consumers of your API use with HQL, then a naming strategy is needed.

nosetter

NHibernate will access the field directly when setting the value and will use the Property when getting the value. This can be used when a property only exposes a get accessor because the consumers of your API can't change the value directly. A naming strategy is required because NHibernate uses the value of the name attribute as the property name and needs to be told what the name of the field is.

ClassName

If NHibernate's built in access strategies are not what is needed for your situation then you can build your own by implementing the interface NHibernate.Property.IPropertyAccessor. The value of the access attribute should be an assembly-qualified name that can be loaded with Activator.CreateInstance(string assemblyQualifiedName).

Table 5.2. Naming Strategies

Naming Strategy NameDescription
camelcase

The name attribute is converted to camel case to find the field. <property name="Foo" ... > uses the field foo.

camelcase-underscore

The name attribute is converted to camel case and prefixed with an underscore to find the field. <property name="Foo" ... > uses the field _foo.

lowercase

The name attribute is converted to lower case to find the Field. <property name="FooBar" ... > uses the field foobar.

lowercase-underscore

The name attribute is converted to lower case and prefixed with an underscore to find the Field. <property name="FooBar" ... > uses the field _foobar.

pascalcase-underscore

The name attribute is prefixed with an underscore to find the field. <property name="Foo" ... > uses the field _Foo.

pascalcase-m

The name attribute is prefixed with the character m to find the field. <property name="Foo" ... > uses the field mFoo.

pascalcase-m-underscore

The name attribute is prefixed with the character m and an underscore to find the field. <property name="Foo" ... > uses the field m_Foo.

5.1.10. many-to-one

An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association. (It's really just an object reference.)

<many-to-one
        name="PropertyName"                                (1)
        column="column_name"                               (2)
        class="ClassName"                                  (3)
        cascade="all|none|save-update|delete"              (4)
        fetch="join|select"                                (5)
        update="true|false"                                (6)
        insert="true|false"                                (6)
        property-ref="PropertyNameFromAssociatedClass"     (7)
        access="field|property|nosetter|ClassName"         (8)
        unique="true|false"                                (9)
        optimistic-lock="true|false"                       (10)
        not-found="ignore|exception"                       (11)
/>
(1)

name: The name of the property.

(2)

column (optional): The name of the column.

(3)

class (optional - defaults to the property type determined by reflection): The name of the associated class.

(4)

cascade (optional): Specifies which operations should be cascaded from the parent object to the associated object.

(5)

fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

(6)

update, insert (optional - defaults to true) specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized from some other property that maps to the same colum(s) or by a trigger or other application.

(7)

property-ref: (optional) The name of a property of the associated class that is joined to this foreign key. If not specified, the primary key of the associated class is used.

(8)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(9)

unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column.

(10)

optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, dertermines if a version increment should occur when this property is dirty.

(11)

not-found (optional - defaults to exception): Specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association.

The cascade attribute permits the following values: all, save-update, delete, none. Setting a value other than none will propagate certain operations to the associated (child) object. See "Lifecycle Objects" below.

The fetch attribute accepts two different values:

  • join Fetch the association using an outer join

  • select Fetch the association using a separate query

A typical many-to-one declaration looks as simple as

<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

The property-ref attribute should only be used for mapping legacy data where a foreign key refers to a unique key of the associated table other than the primary key. This is an ugly relational model. For example, suppose the Product class had a unique serial number, that is not the primary key. (The unique attribute controls NHibernate's DDL generation with the SchemaExport tool.)

<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>

Then the mapping for OrderItem might use:

<many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/>

This is certainly not encouraged, however.

5.1.11. one-to-one

A one-to-one association to another persistent class is declared using a one-to-one element.

<one-to-one
        name="PropertyName"                                (1)
        class="ClassName"                                  (2)
        cascade="all|none|save-update|delete"              (3)
        constrained="true|false"                           (4)
        fetch="join|select"                                (5)
        property-ref="PropertyNameFromAssociatedClass"     (6)
        access="field|property|nosetter|ClassName"         (7)
/>
(1)

name: The name of the property.

(2)

class (optional - defaults to the property type determined by reflection): The name of the associated class.

(3)

cascade (optional) specifies which operations should be cascaded from the parent object to the associated object.

(4)

constrained (optional) specifies that a foreign key constraint on the primary key of the mapped table references the table of the associated class. This option affects the order in which Save() and Delete() are cascaded (and is also used by the schema export tool).

(5)

fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

(6)

property-ref: (optional) The name of a property of the associated class that is joined to the primary key of this class. If not specified, the primary key of the associated class is used.

(7)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

There are two varieties of one-to-one association:

  • primary key associations

  • unique foreign key associations

Primary key associations don't need an extra table column; if two rows are related by the association then the two table rows share the same primary key value. So if you want two objects to be related by a primary key association, you must make sure that they are assigned the same identifier value!

For a primary key association, add the following mappings to Employee and Person, respectively.

<one-to-one name="Person" class="Person"/>
<one-to-one name="Employee" class="Employee" constrained="true"/>

Now we must ensure that the primary keys of related rows in the PERSON and EMPLOYEE tables are equal. We use a special NHibernate identifier generation strategy called foreign:

<class name="Person" table="PERSON">
    <id name="Id" column="PERSON_ID">
        <generator class="foreign">
            <param name="property">Employee</param>
        </generator>
    </id>
    ...
    <one-to-one name="Employee"
        class="Employee"
        constrained="true"/>
</class>

A newly saved instance of Person is then assigned the same primar key value as the Employee instance refered with the Employee property of that Person.

Alternatively, a foreign key with a unique constraint, from Employee to Person, may be expressed as:

<many-to-one name="Person" class="Person" column="PERSON_ID" unique="true"/>

And this association may be made bidirectional by adding the following to the Person mapping:

<one-to-one name="Employee" class="Employee" property-ref="Person"/>

5.1.12. component, dynamic-component

The <component> element maps properties of a child object to columns of the table of a parent class. Components may, in turn, declare their own properties, components or collections. See "Components" below.

<component 
        name="PropertyName"                                (1)
        class="ClassName"                                  (2)
        insert="true|false"                                (3)
        upate="true|false"                                 (4)
        access="field|property|nosetter|ClassName"         (5)
        optimistic-lock="true|false"                       (6)
>
        
        <property ...../>
        <many-to-one .... />
        ........
</component>
(1)

name: The name of the property.

(2)

class (optional - defaults to the property type determined by reflection): The name of the component (child) class.

(3)

insert: Do the mapped columns appear in SQL INSERTs?

(4)

update: Do the mapped columns appear in SQL UPDATEs?

(5)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(6)

optimistic-lock (optional - defaults to true): Specifies that updates to this component do or do not require acquisition of the optimistic lock. In other words, determines if a version increment should occur when this property is dirty.

The child <property> tags map properties of the child class to table columns.

The <component> element allows a <parent> subelement that maps a property of the component class as a reference back to the containing entity.

The <dynamic-component> element allows an IDictionary to be mapped as a component, where the property names refer to keys of the dictionary.

5.1.13. subclass

Finally, polymorphic persistence requires the declaration of each subclass of the root persistent class. For the (recommended) table-per-class-hierarchy mapping strategy, the <subclass> declaration is used.

<subclass
        name="ClassName"                              (1)
        discriminator-value="discriminator_value"     (2)
        proxy="ProxyInterface"                        (3)
        lazy="true|false"                             (4)
        dynamic-update="true|false"
        dynamic-insert="true|false">

        <property .... />
        .....
</subclass>
(1)

name: The fully qualified .NET class name of the subclass, including its assembly name.

(2)

discriminator-value (optional - defaults to the class name): A value that distiguishes individual subclasses.

(3)

proxy (optional): Specifies a class or interface to use for lazy initializing proxies.

(4)

lazy (optional, defaults to true): Setting lazy="false" disables the use of lazy fetching.

Each subclass should declare its own persistent properties and subclasses. <version> and <id> properties are assumed to be inherited from the root class. Each subclass in a hierarchy must define a unique discriminator-value. If none is specified, the fully qualified .NET class name is used.

5.1.14. joined-subclass

Alternatively, a subclass that is persisted to its own table (table-per-subclass mapping strategy) is declared using a <joined-subclass> element.

<joined-subclass
        name="ClassName"                    (1)
        proxy="ProxyInterface"              (2)
        lazy="true|false"                   (3)
        dynamic-update="true|false"
        dynamic-insert="true|false">

        <key .... >

        <property .... />
        .....
</joined-subclass>
(1)

name: The fully qualified class name of the subclass.

(2)

proxy (optional): Specifies a class or interface to use for lazy initializing proxies.

(3)

lazy (optional): Setting lazy="true" is a shortcut equalivalent to specifying the name of the class itself as the proxy interface.

No discriminator column is required for this mapping strategy. Each subclass must, however, declare a table column holding the object identifier using the <key> element. The mapping at the start of the chapter would be re-written as:

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Eg"
    namespace="Eg">

        <class name="Cat" table="CATS">
                <id name="Id" column="uid" type="Int64">
                        <generator class="hilo"/>
                </id>
                <property name="BirthDate" type="Date"/>
                <property name="Color" not-null="true"/>
                <property name="Sex" not-null="true"/>
                <property name="Weight"/>
                <many-to-one name="Mate"/>
                <set name="Kittens">
                        <key column="MOTHER"/>
                        <one-to-many class="Cat"/>
                </set>
                <joined-subclass name="DomesticCat" table="DOMESTIC_CATS">
                    <key column="CAT"/>
                        <property name="Name" type="String"/>
                </joined-subclass>
        </class>

        <class name="Dog">
                <!-- mapping for Dog could go here -->
        </class>

</hibernate-mapping>

5.1.15. map, set, list, bag

Collections are discussed later.

5.1.16. import

Suppose your application has two persistent classes with the same name, and you don't want to specify the fully qualified name in NHibernate queries. Classes may be "imported" explicitly, rather than relying upon auto-import="true". You may even import classes and interfaces that are not explicitly mapped.

<import class="System.Object" rename="Universe"/>
<import
        class="ClassName"              (1)
        rename="ShortName"             (2)
/>
(1)

class: The fully qualified class name of any .NET class, including its assembly name.

(2)

rename (optional - defaults to the unqualified class name): A name that may be used in the query language.

5.2. NHibernate Types

5.2.1. Entities and values

To understand the behaviour of various .NET language-level objects with respect to the persistence service, we need to classify them into two groups:

An entity exists independently of any other objects holding references to the entity. Contrast this with the usual Java model where an unreferenced object is garbage collected. Entities must be explicitly saved and deleted (except that saves and deletions may be cascaded from a parent entity to its children). This is different from the ODMG model of object persistence by reachability - and corresponds more closely to how application objects are usually used in large systems. Entities support circular and shared references. They may also be versioned.

An entity's persistent state consists of references to other entities and instances of value types. Values are primitives, collections, components and certain immutable objects. Unlike entities, values (in particular collections and components) are persisted and deleted by reachability. Since value objects (and primitives) are persisted and deleted along with their containing entity they may not be independently versioned. Values have no independent identity, so they cannot be shared by two entities or collections.

All NHibernate types except collections support null semantics if the .NET type is nullable (i.e. not derived from System.ValueType).

Up until now, we've been using the term "persistent class" to refer to entities. We will continue to do that. Strictly speaking, however, not all user-defined classes with persistent state are entities. A component is a user defined class with value semantics.

5.2.2. Basic value types

The basic types may be roughly categorized into three groups - System.ValueType types, System.Object types, and System.Object types for large objects. Just like the .NET Types, columns for System.ValueType types can not store null values and System.Object types can store null values.

Table 5.3. System.ValueType Mapping Types

NHibernate Type.NET TypeDatabase TypeRemarks
AnsiCharSystem.CharDbType.AnsiStringFixedLength - 1 char 
BooleanSystem.BooleanDbType.BooleanDefault when no type attribute specified.
ByteSystem.ByteDbType.ByteDefault when no type attribute specified.
CharSystem.CharDbType.StringFixedLength - 1 charDefault when no type attribute specified.
DateTimeSystem.DateTimeDbType.DateTime - ignores the millisecondsDefault when no type attribute specified.
DecimalSystem.DecimalDbType.DecimalDefault when no type attribute specified.
DoubleSystem.DoubleDbType.DoubleDefault when no type attribute specified.
GuidSystem.GuidDbType.GuidDefault when no type attribute specified.
Int16System.Int16DbType.Int16Default when no type attribute specified.
Int32System.Int32DbType.Int32Default when no type attribute specified.
Int64System.Int64DbType.Int64Default when no type attribute specified.
PersistentEnumA System.EnumThe DbType for the underlying value.Do not specify type="PersistentEnum" in the mapping. Instead specify the Assembly Qualified Name of the Enum or let NHibernate use Reflection to "guess" the Type. The UnderlyingType of the Enum is used to determine the correct DbType.
SingleSystem.SingleDbType.SingleDefault when no type attribute specified.
TicksSystem.DateTimeDbType.Int64type="Ticks" must be specified.
TimeSpanSystem.TimeSpanDbType.Int64Default when no type attribute specified.
TimestampSystem.DateTimeDbType.DateTime - as specific as database supports.type="Timestamp" must be specified.
TrueFalseSystem.BooleanDbType.AnsiStringFixedLength - 1 char either 'T' or 'F'type="TrueFalse" must be specified.
YesNoSystem.BooleanDbType.AnsiStringFixedLength - 1 char either 'Y' or 'N'type="YesNo" must be specified.

Table 5.4. System.Object Mapping Types

NHibernate Type.NET TypeDatabase TypeRemarks
AnsiStringSystem.StringDbType.AnsiStringtype="AnsiString" must be specified.
CultureInfoSystem.Globalization.CultureInfoDbType.String - 5 chars for cultureDefault when no type attribute specified.
BinarySystem.Byte[]DbType.BinaryDefault when no type attribute specified.
TypeSystem.TypeDbType.String holding Assembly Qualified Name.Default when no type attribute specified.
StringSystem.StringDbType.StringDefault when no type attribute specified.

Table 5.5. Large Object Mapping Types

NHibernate Type.NET TypeDatabase TypeRemarks
StringClobSystem.StringDbType.Stringtype="StringClob" must be specified. Entire field is read into memory.
BinaryBlobSystem.Byte[]DbType.Binarytype="BinaryBlob" must be specified. Entire field is read into memory.
SerializableAny System.Object that is marked with SerializableAttribute.DbType.Binarytype="Serializable" should be specified. This is the fallback type if no NHibernate Type can be found for the Property.

NHibernate supports some additional type names for compatibility with Hibernate (useful for those coming over from Hibernate or using some of the tools to generate hbm.xml files). A type="integer" or type="int" will map to an Int32 NHibernate type, type="short" to an Int16 NHibernateType. To see all of the conversions you can view the source of static constructor of the class NHibernate.Type.TypeFactory.

5.2.3. Custom value types

It is relatively easy for developers to create their own value types. For example, you might want to persist properties of type Int64 to VARCHAR columns. NHibernate does not provide a built-in type for this. But custom types are not limited to mapping a property (or collection element) to a single table column. So, for example, you might have a property Name { get; set; } of type String that is persisted to the columns FIRST_NAME, INITIAL, SURNAME.

To implement a custom type, implement either NHibernate.UserTypes.IUserType or NHibernate.UserTypes.ICompositeUserType and declare properties using the fully qualified name of the type. Check out NHibernate.DomainModel.DoubleStringType to see the kind of things that are possible.

<property name="TwoStrings" type="NHibernate.DomainModel.DoubleStringType, NHibernate.DomainModel">
    <column name="first_string"/>
    <column name="second_string"/>
</property>

Notice the use of <column> tags to map a property to multiple columns.

The ICompositeUserType, IEnhancedUserType, INullableUserType, IUserCollectionType, and IUserVersionType interfaces provide support for more specialized uses.

You may even supply parameters to an IUserType in the mapping file. To do this, your IUserType must implement the NHibernate.UserTypes.IParameterizedType interface. To supply parameters to your custom type, you can use the <type> element in your mapping files.

<property name="priority">
    <type name="MyCompany.UserTypes.DefaultValueIntegerType">
        <param name="default">0</param>
    </type>
</property>

The IUserType can now retrieve the value for the parameter named default from the IDictionary object passed to it.

Even though NHibernate's rich range of built-in types and support for components means you will very rarely need to use a custom type, it is nevertheless considered good form to use custom types for (non-entity) classes that occur frequently in your application. For example, a MonetaryAmount class is a good candidate for an ICompositeUserType, even though it could easily be mapped as a component. One motivation for this is abstraction. With a custom type, your mapping documents would be future-proofed against possible changes in your way of representing monetary values.

5.2.4. Any type mappings

There is one further type of property mapping. The <any> mapping element defines a polymorphic association to classes from multiple tables. This type of mapping always requires more than one column. The first column holds the type of the associated entity. The remaining columns hold the identifier. It is impossible to specify a foreign key constraint for this kind of association, so this is most certainly not meant as the usual way of mapping (polymorphic) associations. You should use this only in very special cases (eg. audit logs, user session data, etc).

<any name="AnyEntity" id-type="Int64" meta-type="Eg.Custom.Class2TablenameType">
    <column name="table_name"/>
    <column name="id"/>
</any>

The meta-type attribute lets the application specify a custom type that maps database column values to persistent classes which have identifier properties of the type specified by id-type. If the meta-type returns instances of System.Type, nothing else is required. On the other hand, if it is a basic type like String or Char, you must specify the mapping from values to classes.

<any name="AnyEntity" id-type="Int64" meta-type="String">
    <meta-value value="TBL_ANIMAL" class="Animal"/>
    <meta-value value="TBL_HUMAN" class="Human"/>
    <meta-value value="TBL_ALIEN" class="Alien"/>
    <column name="table_name"/>
    <column name="id"/>
</any>
<any
        name="PropertyName"                                (1)
        id-type="idtypename"                               (2)
        meta-type="metatypename"                           (3)
        cascade="none|all|save-update"                     (4)
        access="field|property|nosetter|ClassName"         (5)
        optimistic-lock="true|false"                       (6)
>
        <meta-value ... />
        <meta-value ... />
        .....
        <column .... />
        <column .... />
        .....
</any>
(1)

name: the property name.

(2)

id-type: the identifier type.

(3)

meta-type (optional - defaults to Type): a type that maps System.Type to a single database column or, alternatively, a type that is allowed for a discriminator mapping.

(4)

cascade (optional - defaults to none): the cascade style.

(5)

access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.

(6)

optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, define if a version increment should occur if this property is dirty.

5.3. SQL quoted identifiers

You may force NHibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document. NHibernate will use the correct quotation style for the SQL Dialect (usually double quotes, but brackets for SQL Server and backticks for MySQL).

<class name="LineItem" table="`Line Item`">
    <id name="Id" column="`Item Id`"/><generator class="assigned"/></id>
    <property name="ItemNumber" column="`Item #`"/>
    ...
</class>

5.4. Modular mapping files

It is possible to define subclass and joined-subclass mappings in seperate mapping documents, directly beneath hibernate-mapping. This allows you to extend a class hierachy just by adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming a previously mapped superclass. Use of this feature makes the ordering of the mapping documents important!

<hibernate-mapping>
        <subclass name="Eg.Subclass.DomesticCat, Eg"
            extends="Eg.Cat, Eg" discriminator-value="D">
             <property name="name" type="string"/>
        </subclass>
</hibernate-mapping>