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, even transparently at runtime. This includes the NHibernate.Mapping.Attributes library which allows to directly annotate your entities with mapping declarations, various template-based code generators (CodeSmith, MyGeneration), the built-in NHibernate.Mapping.ByCode API available since NHibernate 3.2, or the Fluent NHibernate independent library.

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 mainly 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 column sub-element of a property.

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 as part of any project in your solution, (Build Action can be "None") or as "Solution Files" or in your "Lib" folder and then add it to the Schemas property of the xml file. You can copy it in <VS installation directory>\Xml\Schemas, take care because you will have to deal with different version of the xsd for different versions of NHibernate.

5.1.2. hibernate-mapping

This element has several optional attributes. The schema and catalog attributes specify that tables referred to by this mapping belong to the named schema and/or catalog. If they are specified, table names will be qualified by the given schema and/or catalog name. If they are missing, table names 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)
    catalog="catalogName"                             (2)
    default-cascade="none|save-update..."             (3)
    auto-import="true|false"                          (4)
    assembly="Eg"                                     (5)
    namespace="Eg"                                    (6)
    default-access="field|property|field.camelcase..."(7)
    default-lazy="true|false"                         (8)
 />
(1)

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

(2)

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

(3)

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

(4)

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

(5)(6)

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

(7)

default-access (optional - defaults to property): The strategy NHibernate should use for accessing a property value. It can be a custom implementation of IPropertyAccessor.

(8)

default-lazy (optional - defaults to true): The default value for unspecified lazy attributes of class and collection mappings.

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.

The hibernate-mapping element allows you to nest several persistent <class> mappings, as shown above. It is, however, good practice to map only a single persistent class, or a single class hierarchy, in one mapping file and name it after the persistent super-class. For example, Cat.hbm.xml, Dog.hbm.xml, or if using inheritance, Animal.hbm.xml.

5.1.3. class

You may declare a persistent class using the class element:

<class
    name="className"                                  (1)
    table="tableName"                                 (2)
    discriminator-value="discriminatorValue"          (3)
    mutable="true|false"                              (4)
    schema="owner"                                    (5)
    catalog="catalog"                                 (6)
    proxy="proxyInterface"                            (7)
    dynamic-update="true|false"                       (8)
    dynamic-insert="true|false"                       (9)
    select-before-update="true|false"                 (10)
    polymorphism="implicit|explicit"                  (11)
    where="arbitrary sql where condition"             (12)
    persister="persisterClass"                        (13)
    batch-size="N"                                    (14)
    optimistic-lock="none|version|dirty|all"          (15)
    lazy="true|false"                                 (16)
    abstract="true|false"                             (17)
    entity-name="entityName"                          (18)
    check="arbitrary sql check condition"             (19)
    subselect="SQL expression"                        (20)
    schema-action="none|drop|update|export|validate|all|commaSeparatedValues"  (21)
    rowid="unused"                                    (22)
    node="unused"                                     (23)
/>
(1)

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

(2)

table(optional - defaults to the unqualified class name): The name of its database table.

(3)

discriminator-value (optional, defaults to the class name): A value that distinguishes 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): Overrides the schema name specified by the root <hibernate-mapping> element.

(6)

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

(7)

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

(8)

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

(9)

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.

(10)

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.

(11)

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

(12)

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

(13)

persister (optional): Specifies a custom IClassPersister.

(14)

batch-size (optional - defaults to 1): Specifies a "batch size" for fetching instances of this class by identifier. See Section 21.1.5, “Using batch fetching”.

(15)

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

(16)

lazy (optional - defaults to true): Lazy fetching can be disabled by setting lazy="false".

(17)

abstract (optional - defaults to false): Used to mark abstract super-classes in <union-subclass> hierarchies.

(18)

entity-name (optional - defaults to the class name): NHibernate allows a class to be mapped multiple times, potentially to different tables. See Section 5.3, “Mapping a class more than once”. It also allows entity mappings that are represented by dictionaries at the .Net level. In these cases, you should provide an explicit arbitrary name for the entity. See Section 4.4, “Dynamic models” for more information.

(19)

check (optional): An SQL expression used to generate a multi-row check constraint for automatic schema generation.

(20)

subselect (optional): Maps an immutable and read-only entity to a database sub-select. This is useful if you want to have a view instead of a base table. See Section 5.1.4, “subselect” for more information.

(21)

schema-action (optional): Specifies which schema actions should be generated for the class table by the schema export tool. Valid values are none, drop, update, export, validate, all and any combination of them separated by commas (,). Not specifying it is treated as all. See Section 22.1, “Schema Generation”.

(22)(23)

rowid and node (optional): These attributes have no usage in NHibernate. The node attribute is present on many more mapping elements, and has no usage on them too. It will be omitted from the documentation of these other elements.

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, unless assigning to them an entity-name without the + character.

Changes to immutable classes, mutable="false", will not be persisted. This allows NHibernate to make some minor performance optimizations.

The optional proxy attribute enables customization of the generated proxy for lazy initialization of persistent instances of the class: by default, the proxy derives from the class. Specifying an interface causes the proxy to implement it and to use System.Object as its base class. This enables proxifying a sealed class or a class having non virtual members. The specified interface should declare all the public members of the persistent class. On ISession.Load and on many-to-one associations, NHibernate will initially return proxies. The actual persistent object will be loaded when a method or property of the proxy is invoked. See Section 21.1.4, “Initializing collections and proxies”.

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 reattach a graph of detached instances to an ISession.

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).

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. subselect

An alternative to mapping a class to table or view columns is to map a query. For that, we use the <subselect> element, which is mutually exclusive with <subclass>, <joined-subclass> and <union-subclass>. The subselect may also be specified as a <class> attribute. The content of the subselect element is a SQL query:

<subselect>
    <![CDATA[
    SELECT cat.ID, cat.NAME, cat.SEX, cat.MATE FROM cat
    ]]>
</subselect>

Usually, when mapping a query using subselect you will want to mark the class as not mutable (mutable="false"), unless you specify custom SQL for performing the UPDATE, DELETE and INSERT operations.

Also, it makes sense to force synchronization of the tables affected by the query, using one or more <synchronize> entries:

<subselect>
    <![CDATA[
    SELECT cat.ID, cat.NAME, cat.SEX, cat.MATE FROM cat
    ]]>
</subselect>
<synchronize table="cat"/>

This ensures that auto-flush happens correctly and that queries against the derived entity do not return stale data.

You then still have to declare the class id and properties.

5.1.5. 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)
    length="typeLength"                               (3)
    column="columnName"                               (4)
    unsaved-value="any|none|null|undefined|idValue"   (5)
    access="field|property|nosetter|className"        (6)
    generator="generatorClass">                       (7)

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

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

(2)

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

(3)

length (optional): If the type takes a length and does not already specify it, its length.

(4)

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

(5)

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.

(6)

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

(7)

generator: The name of a generator class to use for generating unique identifiers for instances of the persistent class. See the generator element. Specifying either the attribute or the element is required. The attribute takes precedence over the element.

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.

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.5.1. generator

The required generator names a .NET class used to generate unique identifiers for instances of the persistent class.

The generator can be declared using the <generator> child element. If any parameters are required to configure or initialize the generator instance, they are passed using <param> elements.

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

If no parameters are required, the generator can be declared using a generator attribute directly on the <id> element, as follows:

<id name="Id" type="Int64" column="uid" generator="native" />

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.

counter, vm

generates identifiers of 64bits integral type constructed from the system time and a counter value. Do not use in a cluster. May generate colliding identifiers in a bit less than one year.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and some other systems. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported. See Section 5.1.5.6, “Identity columns and Sequences”.

sequence

uses a sequence in DB2, PostgreSQL, Oracle and some other systems, 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. See Section 5.1.5.6, “Identity columns and Sequences”.

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 an user-supplied connection. See Section 5.1.5.2, “Hi/Lo Algorithm”.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of any integral type, given a named database sequence. See Section 5.1.5.2, “Hi/Lo Algorithm”.

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. See Section 5.1.5.3, “UUID Hex Algorithm”.

uuid.string

uses a new System.Guid to create a byte[] that is converted to a string. See Section 5.1.5.4, “UUID String Algorithm”.

guid

uses a new System.Guid as the identifier. It is not equivalent to the Hibernate guid generator. See Section 5.1.5.5, “GUID Algorithms”.

guid.comb

uses the algorithm to generate a new System.Guid described by Jimmy Nilsson in this article. See also Section 5.1.5.5, “GUID Algorithms”.

guid.native

uses the database server side Guid function.

native

picks identity, sequence or hilo depending upon the capabilities of the underlying database. See Section 5.1.5.6, “Identity columns and Sequences”.

assigned

lets the application to assign an identifier to the object before Save() is called. See Section 5.1.5.7, “Assigned Identifiers”.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value. See Section 5.1.5.8, “Primary keys assigned by triggers”.

foreign

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

sequence-identity

a generator which combines sequence generation with immediate retrieval by attaching an output parameter to the SQL command. In this respect it works much like ANSI-SQL identity generation.

trigger-identity

a generator which uses an output parameter to return the identifier generated by the insert on database server side.

enhanced-sequence

uses a sequence with database supporting them, otherwise uses a table for emulating the sequence. See Section 5.1.5.9, “Enhanced identifier generators”. Supports Section 5.1.5.9.1, “Identifier generator optimization”.

enhanced-table

uses a table like the hilo generator, but can handle multiple increment values per table. See Section 5.1.5.9, “Enhanced identifier generators”. Supports Section 5.1.5.9.1, “Identifier generator optimization”.

5.1.5.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).

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

<id name="Id" type="Int64" column="cat_id">
    <generator class="hilo">
        <param name="table">tableName</param>
        <param name="column">columnName</param>
        <param name="schema">schemaName</param>
        <param name="catalog">catalogName</param>
        <param name="max_lo">100</param>
        <param name="where">arbitraryWhereClause</param>
    </generator>
</id>

table defaults to hibernate_unique_key, column defaults to next_hi, and max_lo defaults to 32767. schema, catalog and where are optional and have no default value.

You can use the optional where parameter to specify the row to use in a table. This is useful if you want to use a single table for your identifiers, with different rows for each table. Do not include the where keyword in its value. This is not handled by NHibernate schema generation tooling.

<id name="Id" type="Int64" column="cat_id">
    <generator class="seqhilo">
        <param name="sequence">hi_value</param>hibernate_sequence
        <param name="schema">schemaName</param>
        <param name="catalog">catalogName</param>
        <param name="max_lo">100</param>
        <param name="parameters">arbitrarySqlFragment</param>
    </generator>
</id>

sequence defaults to hibernate_sequence, and max_lo defaults to 9. schema, catalog and parameters are optional and have no default value.

You can use the optional parameters parameter to specify some SQL to be appended to the create sequence DDL.

5.1.5.3. UUID Hex Algorithm

<id name="Id" type="String" column="cat_id">
    <generator class="uuid.hex">
        <param name="format">format_value</param>
        <param name="separator">separator_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 separator is - and should rarely be modified. The format determines if the configured separator can replace the default separator used by the format.

5.1.5.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.5.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.5.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">
    <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.5.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 may, when saved via the ISession's SaveOrUpdate() method, cause NHibernate to query the database for checking if the entity exist or not.

To avoid this, either:

  • ensure that the identifier unsaved-value is not defined or is set to undefined, and define an unsaved-value on a <version> or <timestamp> property mapping for the class. (Depending on the version type, its default unsaved-value will generally already be suitable.)

  • specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

  • set unsaved-value="none" and explicitly Save() newly instantiated objects.

  • set unsaved-value="any" and explicitly Update() previously persistent objects.

  • implement IInterceptor.IsTransient() for providing your own strategy for distinguishing newly instantiated objects. See Section 13.1, “Interceptors”.

For assigned identifiers, unsaved-value default value is undefined.

5.1.5.8. Primary keys assigned by triggers

NHibernate does not generate DDL with triggers. It is for legacy schemas only.

<id name="id" type="long" column="person_id">
    <generator class="select">
        <param name="key">socialSecurityNumber</param>
    </generator>
</id>

In the above example, there is a unique valued property named socialSecurityNumber. It is defined by the class, as a property. And a surrogate key named person_id has its value generated by a trigger. Its value will be retrieved by querying the entity table filtered by the key property.

If the class maps a natural id, key can be omitted. The natural id will be used when key is omitted.

5.1.5.9. Enhanced identifier generators

Starting with NHibernate release 3.3.0, there are two new generators which represent a re-thinking of two different aspects of identifier generation. The first aspect is database portability; the second is optimization. Optimization means that you do not have to query the database for every request for a new identifier value. These two new generators are intended to take the place of some of the named generators described above.

The first of these new generators is NHibernate.Id.Enhanced.SequenceStyleGenerator (short name enhanced-sequence) which is intended, firstly, as a replacement for the sequence generator and, secondly, as a better portability generator than native. This is because native generally chooses between identity and sequence which have largely different semantics that can cause subtle issues in applications eyeing portability. NHibernate.Id.Enhanced.SequenceStyleGenerator, however, achieves portability in a different manner. It chooses between a table or a sequence in the database to store its incrementing values, depending on the capabilities of the dialect being used. The difference between this and native is that table-based and sequence-based storage have the same exact semantic. In fact, sequences are exactly what NHibernate tries to emulate with its table-based generators. This generator has a number of configuration parameters:

  • sequence_name (optional - defaults to hibernate_sequence): the name of the sequence or table to be used. schema and catalog parameters can be additionally used to qualify the sequence name.

  • initial_value (optional - defaults to 1): the initial value to be retrieved from the sequence/table. In sequence creation terms, this is analogous to the clause typically named "STARTS WITH".

  • increment_size (optional - defaults to 1): the value by which subsequent calls to the sequence/table should differ. In sequence creation terms, this is analogous to the clause typically named "INCREMENT BY".

  • force_table_use (optional - defaults to false): should we force the use of a table as the backing structure even though the dialect might support sequence?

  • value_column (optional - defaults to next_val): only relevant for table structures, it is the name of the column on the table which is used to hold the value.

  • optimizer (optional - defaults to none if increment_size is 1): See Section 5.1.5.9.1, “Identifier generator optimization”

The second of these new generators is NHibernate.Id.Enhanced.TableGenerator (short name enhanced-table), which is intended, firstly, as a replacement for the table generator, even though it actually functions much more like org.hibernate.id.MultipleHiLoPerTableGenerator (not available in NHibernate), and secondly, as a re-implementation of org.hibernate.id.MultipleHiLoPerTableGenerator (not available in NHibernate) that utilizes the notion of pluggable optimizers. Essentially this generator defines a table capable of holding a number of different increment values simultaneously by using multiple distinctly keyed rows. This generator has a number of configuration parameters:

  • table_name (optional - defaults to hibernate_sequences): the name of the table to be used. schema and catalog parameters can be additionally used to qualify the sequence name.

  • value_column_name (optional - defaults to next_val): the name of the column on the table that is used to hold the value.

  • segment_column_name (optional - defaults to sequence_name): the name of the column on the table that is used to hold the "segment key". This is the value which identifies which increment value to use.

  • segment_value (optional - defaults to default unless prefer_entity_table_as_segment_value is true): The "segment key" value for the segment from which we want to pull increment values for this generator.

  • segment_value_length (optional - defaults to 255): Used for schema generation; the column size to create this segment key column.

  • prefer_entity_table_as_segment_value (optional - defaults to false): If segment_value is not specified, whether it should defaults to the entity table name or to default.

  • initial_value (optional - defaults to 1): The initial value to be retrieved from the table.

  • increment_size (optional - defaults to 1): The value by which subsequent calls to the table should differ.

  • optimizer (optional - defaults to none if increment_size is 1): See Section 5.1.5.9.1, “Identifier generator optimization”.

5.1.5.9.1. Identifier generator optimization

For identifier generators that store values in the database, it is inefficient for them to hit the database on each and every call to generate a new identifier value. Instead, you can group a bunch of them in memory and only hit the database when you have exhausted your in-memory value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators (Section 5.1.5.9, “Enhanced identifier generators” support this operation.

  • none (generally this is the default if no optimizer was specified): this will not perform any optimizations and hit the database for each and every request.

  • hilo: applies a hi/lo algorithm around the database retrieved values. The values from the database for this optimizer are expected to be sequential. The values retrieved from the database structure for this optimizer indicates the "group number". The increment_size is multiplied by that value in memory to define a group "hi value".

  • pooled: as with the case of hilo, this optimizer attempts to minimize the number of hits to the database. Here, however, we simply store the starting value for the "next group" into the database structure rather than a sequential value in combination with an in-memory grouping algorithm. Here, increment_size refers to the values coming from the database.

  • pooled-lo: similar to pooled, except that it's the starting value of the "current group" that is stored into the database structure. Here, increment_size refers to the values coming from the database.

5.1.6. composite-id

<composite-id
    name="propertyName"
    class="className"
    unsaved-value="any|none"
    access="field|property|nosetter|className"
    mapped="true|false">

    <key-property name="propertyName" type="typeName" column="columnName"/>
    <key-many-to-one name="propertyName class="className" column="columnName"/>
    ...
</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 marked with the Serializable attribute.

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 call this approach an embedded composite identifier, and discourage it for serious applications.

  • unsaved-value (optional - default to undefined): controls how transient instances are considered. any assumes any transient instance is newly instantiated. In other words, the instance will be saved (inserted in the database). none assumes any transient instance is already persisted. In other words, the instance will be updated. undefined does not assume anything: NHibernate may query the database for determining if the entity is already persisted or not.

  • mapped (optional - defaults to false): This attribute has no usage in NHibernate.

A much more convenient approach is to implement the composite identifier as a separate class, as in Section 8.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 Section 8.4, “Components as composite identifiers”).

  • 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.

The second approach, an identifier component, is recommended for almost all applications.

5.1.7. 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="discriminatorColumn"                      (1)
    type="discriminatorType"                          (2)
    length="typeLength"                               (3)
    not-null="true|false"                             (4)
    force="true|false"                                (5)
    insert="true|false"                               (6)
    formula="arbitrary SQL expression"                (7)
/>
(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)

length (optional): if the type takes a length and does not already specify it, its length.

(4)

not-null (optional - defaults to true): sets the column nullability for DDL generation.

(5)

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

(6)

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

(7)

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.8. 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 Section 12.4, “Optimistic concurrency control”).

<version
    column="versionColumn"                            (1)
    name="propertyName"                               (2)
    type="typeName"                                   (3)
    access="field|property|nosetter|className"        (4)
    unsaved-value="null|negative|undefined|value"     (5)
    generated="never|always"                          (6)
    insert="false|true"                               (7)
/>
(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 nothing should be assumed from the version property. The identifier check on its own unsaved-value will take precedence, unless its own value is undefined.

(6)

generated (optional - defaults to never): Specifies that this version property value is actually generated by the database. See the discussion of generated properties.

(7)

insert (optional - defaults to false): This attribute has no usage in NHibernate.

Version may be of type Int64, Int32, Int16, Ticks, Timestamp, TimeSpan, datetimeoffset, ... (or their nullable counterparts in .NET 2.0 and higher). Any type implementing IVersionType is usable as a version.

5.1.9. 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="timestampColumn"                          (1)
    name="propertyName"                               (2)
    access="field|property|nosetter|className"        (3)
    unsaved-value="null|undefined"                    (4)
    generated="never|always"                          (5)
    source="vm|db"                                    (6)
/>
(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 nothing should be assumed from the timestamp value. The identifier check on its own unsaved-value will take precedence, unless its own value is undefined.

(5)

generated (optional - defaults to never): Specifies that this timestamp property value is actually generated by the database on insert and updates. See the discussion of generated properties. It should not to be confused with source value db, which mandates NHibernate to retrieve the timestamp from the database in a dedicated query, in order to get the new value to set in the next insert or update.

(6)

source (optional - defaults to vm): Where should NHibernate retrieve the timestamp value from? From the database, or from the current runtime? Database-based timestamps incur an overhead because NHibernate must hit the database in order to determine the "next value". It is safer to use in clustered environments. Not all dialects are known to support the retrieval of the database's current timestamp. Others may also be unsafe for usage in locking due to lack of precision.

Note that <timestamp> is equivalent to <version type="datetime">, and <timestamp source="db"> is equivalent to <version type="dbtimestamp">.

5.1.10. property

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

<property
    name="propertyName"                               (1)
    column="columnName"                               (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)
    generated="never|insert|always"                   (8)
    lazy="true|false"                                 (9)
    lazy-group="groupName"                            (10)
    not-null="true|false"                             (11)
    unique="true|false"                               (12)
    unique-key="uniqueKeyName"                        (13)
    index="indexName"                                 (14)
    length="L"                                        (15)
    precision="P"                                     (16)
    scale="S"                                         (17)
/>
(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.

(8)

generated (optional - defaults to never): specifies that this property value is actually generated by the database. See the discussion of generated properties.

(9)

lazy (optional - defaults to false): specifies that this property is lazy. A lazy property is not loaded when the object is initially loaded, unless the fetch mode has been overridden in a specific query. Values for lazy properties are loaded per lazy-group.

Having lazy properties causes instances of the entity to be loaded as proxies. Theses proxies ignore the class proxy setting and always derives from the persistent class, requiring its members to be overridable.

(10)

lazy-group (optional - defaults to DEFAULT): if the property is lazy, its lazy-loading group. When a lazy property is accessed, the other lazy properties of the lazy group are also loaded with it.

(11)

not-null (optional - defaults to false): sets the column nullability for DDL generation.

(12)

unique (optional - defaults to false): sets the column uniqueness for DDL generation. Use unique-key instead if the value is unique only in combination with other properties.

(13)

unique-key (optional): a logical name for an unique index for DDL generation. The column will be included in the index, along with other columns sharing the same unique-key logical name. The actual index name depends on the dialect.

(14)

index (optional): a logical name for an index for DDL generation. The column will be included in the index, along with other columns sharing the same index logical name. The actual index name depends on the dialect.

(15)

length (optional): if the type takes a length and does not already specify it, its length.

(16)

precision (optional): if the type takes a precision and does not already specify it, its precision.

(17)

scale (optional): if the type takes a scale and does not already specify it, its scale.

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.UtcDateTime, or to specify a custom type.)

See also Section 5.2, “NHibernate Types”.

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.

backfield

NHibernate will access the field of an auto-property directly. This can be used when a property's setter is not accessible.

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.

readonly

Access the mapped property through a Property get to get the value and do nothing to set the value. This is useful to allow calculated properties in the domain that will never be recovered from the DB but can be used for querying.

noop / none

Used to declare properties not represented at the poco level.

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="FooBar" ... > uses the field fooBar.

camelcase-underscore

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

camelcase-m-underscore

The name attribute is converted to camel case and prefixed with the character m and an underscore to find the field. <property name="FooBar" ... > uses the field m_fooBar.

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="FooBar" ... > uses the field _FooBar.

pascalcase-m

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

pascalcase-m-underscore

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

A powerful feature is derived properties. These properties are by definition read-only. The property value is computed at load time. You declare the computation as an SQL expression. This then translates to a SELECT clause subquery in the SQL query that loads an instance:

<property name="totalPrice"
    formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p
                WHERE li.productId = p.productId
                AND li.customerId = customerId
                AND li.orderNumber = orderNumber )"/>

You can reference the entity table by not declaring an alias on a particular column. This would be customerId in the given example. You can also use the nested <formula> mapping element if you do not want to use the attribute.

The nested <column> mapping element can also be used instead of the column attribute.

5.1.11. 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 is really just an object reference.)

<many-to-one
    name="propertyName"                                    (1)
    column="columnName"                                    (2)
    class="className"                                      (3)
    cascade="all|none|save-update|delete|delete-orphan|all-(4)delete-orphan"
    fetch="join|select"                                    (5)
    lazy="proxy|no-proxy|false"                            (6)
    update="true|false"                                    (7)
    insert="true|false"                                    (7)
    property-ref="propertyNameFromAssociatedClass"         (8)
    access="field|property|nosetter|className"             (9)
    optimistic-lock="true|false"                           (10)
    not-found="ignore|exception"                           (11)
    entity-name="entityName"                               (12)
    formula="arbitrary SQL expression"                     (13)
    not-null="true|false"                                  (14)
    unique="true|false"                                    (15)
    unique-key="uniqueKeyName"                             (16)
    index="indexName"                                      (17)
    foreign-key="foreignKeyName"                           (18)
    outer-join="auto|true|false"                           (19)
/>
(1)

name: The name of the property.

(2)

column (optional): The name of the column. This can also be specified by nested <column> element(s).

(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. join takes precedence over the lazy attribute and causes the association to be eagerly fetched.

(6)

lazy (optional - defaults to proxy): By default, single point associations are proxied. lazy="no-proxy" specifies that the property should be fetched lazily when the instance property is first accessed. It works similarly to lazy properties, and causes the entity owning the association to be proxied instead of the association. lazy="false" specifies that the association will be eagerly fetched.

(7)

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 column(s) or by a trigger or other application.

(8)

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.

(9)

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

(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, determines 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.

(12)

entity-name (optional): The entity name of the associated class.

(13)

formula (optional): An SQL expression that defines the value for a computed foreign key.

(14)

not-null (optional - defaults to false): Enables the DDL generation of a nullability constraint for the foreign key column.

(15)

unique (optional - defaults to false): Enables the DDL generation of an unique constraint for the foreign-key column.

(16)

unique-key (optional): A logical name for an unique index for DDL generation. The column will be included in the index, along with other columns sharing the same unique-key logical name. The actual index name depends on the dialect.

(17)

index (optional): A logical name for an index for DDL generation. The column will be included in the index, along with other columns sharing the same index logical name. The actual index name depends on the dialect.

(18)

foreign-key (optional): Specifies the name of the foreign key constraint for DDL generation.

(19)

outer-join (optional): This attribute is obsoleted in favor of fetch. auto is equivalent to not specifying fetch, true is equivalent to join and false is equivalent to select. This obsolete attribute also appears on other elements, with the same usage. It will be omitted from the documentation of these other elements.

Setting a value of the cascade attribute to any meaningful value other than none will propagate certain operations to the associated object. The meaningful values are divided into three categories. First, basic operations, which include: persist, merge, delete, save-update, evict, replicate, lock and refresh; second, special values: delete-orphan; and third, all comma-separated combinations of operation names: cascade="persist,merge,evict" or cascade="all,delete-orphan". See Section 10.10, “Lifecycles and object graphs”.

Here is an example of a typical many-to-one declaration:

<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 a complicated and confusing relational model. For example, if the Product class had a unique serial number that is not the primary key, mapped as below:

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

The unique attribute controls NHibernate's DDL generation with the SchemaExport tool. Then the mapping for OrderItem might use:

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

This is not encouraged, however.

If the referenced unique key comprises multiple properties of the associated entity, you should map the referenced properties inside a named <properties> element.

If the referenced unique key is the property of a component, you can specify a property path:

<many-to-one name="owner" property-ref="Identity.Ssn" column="OWNER_SSN"/>

5.1.12. 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|delete-orphan|all-(3)delete-orphan"
    constrained="true|false"                               (4)
    fetch="join|select"                                    (5)
    lazy="proxy|no-proxy|false"                            (6)
    property-ref="propertyNameFromAssociatedClass"         (7)
    access="field|property|nosetter|className"             (8)
    formula="any SQL expression"                           (9)
    entity-name="entityName"                               (10)
    foreign-key="foreignKeyName"                           (11)
    optimistic-lock="true|false"                           (12)
/>
(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 - default to false): 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 determines whether the association can be proxied. It is also used by the schema export tool.

(5)

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

(6)

lazy (optional - defaults to proxy): By default, single point associations are proxied. lazy="no-proxy" specifies that the property should be fetched lazily when the instance property is first accessed. It works similarly to lazy properties, and causes the entity owning the association to be proxied instead of the association. lazy="false" specifies that the association will be eagerly fetched. Note that if constrained="false", proxying the association is impossible and NHibernate will eagerly fetch the association.

(7)

property-ref: (optional): The name of a property of the associated class that is joined to the primary key of this class (or to the formula of this association). 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)

formula (optional): Almost all one-to-one associations map to the primary key of the owning entity. If this is not the case, you can specify another column or expression to join on using an SQL formula. This can also be specified by nested <formula> element(s).

(10)

entity-name (optional): The entity name of the associated class.

(11)

foreign-key (optional): Specifies the name of the foreign key constraint for DDL generation.

(12)

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.

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 primary key value as the Employee instance referred 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.13. natural-id

<natural-id mutable="true|false"/>
    <property ... />
    <many-to-one ... />
    ...
</natural-id>

Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. Map the properties of the natural key inside the <natural-id> element. NHibernate will generate the necessary unique key and nullability constraints, and your mapping will be more self-documenting.

The <natural-id> element can only appear before the other properties, including version.

We strongly recommend that you implement Equals() and GetHashCode() to compare the natural key properties of the entity.

This mapping is not intended for use with entities with natural primary keys.

  • mutable (optional, defaults to false): By default, natural identifier properties as assumed to be immutable (constant).

5.1.14. 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 Chapter 8, Component Mapping.

<component
    name="propertyName"                                    (1)
    class="className"                                      (2)
    insert="true|false"                                    (3)
    update="true|false"                                    (4)
    access="field|property|nosetter|className"             (5)
    optimistic-lock="true|false"                           (6)
    lazy="true|false"                                      (7)
    lazy-group="groupName"                                 (8)
    unique="true|false">                                   (9)

        <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 (optional - defaults to true): Do the mapped columns appear in SQL INSERTs?

(4)

update (optional - defaults to true): 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.

(7)

lazy (optional - defaults to false): Specifies that this component should be fetched lazily when the instance property is first accessed. For more informations, see lazy on property element.

(8)

lazy-group (optional - defaults to DEFAULT): If the component is lazy, its lazy-loading group. When a lazy property is accessed on an object, included when the property is a component, the other lazy properties of the lazy group are also loaded with it.

(9)

unique (optional - defaults to false): Specifies that an unique constraint exists upon all mapped columns of the component.

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

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

The <dynamic-component> element allows an IDictionary, IDictionary<string, object>, or a C# dynamic to be mapped as a component. When using dictionaries, the property names refer to keys of the dictionary. See Section 8.5, “Dynamic components”.

5.1.15. properties

The <properties> element allows the definition of a named, logical grouping of the properties of a class. The most important use of the construct is that it allows a combination of properties to be the target of a property-ref. It is also a convenient way to define a multi-column unique constraint. For example:

<properties
    name="logicalName"                                     (1)
    insert="true|false"                                    (2)
    update="true|false"                                    (3)
    optimistic-lock="true|false"                           (4)
    unique="true|false">                                   (5)

    <property .../>
    <many-to-one .../>
    ...
</properties>
(1)

name: the logical name of the grouping. It is not an actual property name.

(2)

insert (optional - defaults to true): do the mapped columns appear in SQL INSERTs?

(3)

update (optional - defaults to true): do the mapped columns appear in SQL UPDATEs?

(4)

optimistic-lock (optional - defaults to true): specifies that updates to these properties either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when these properties are dirty.

(5)

unique (optional - defaults to false): specifies that a unique constraint exists upon all mapped columns of the component.

For example, if we have the following <properties> mapping:

<class name="Person">
    <id name="personNumber" />
    <properties name="name" unique="true" update="false">
        <property name="firstName" />
        <property name="lastName" />
        <property name="initial" />
    </properties>
</class>

You might have some legacy data association that refers to this unique key of the Person table, instead of to the primary key:

<many-to-one name="owner" class="Person" property-ref="name">
    <column name="firstName" />
    <column name="lastName" />
    <column name="initial" />
</many-to-one>

The use of this outside the context of mapping legacy data is not recommended.

5.1.16. subclass

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="discriminatorValue"          (2)
    extends="superclassName"                          (3)
    ...>                                              (4)

    <property ... />
    <properties ... />
    ...
</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 distinguishes individual subclasses.

(3)

extends (optional if the <subclass> element is nested into its superclass mapping declaration): Specifies the name of a mapped class as the superclass for the subclass.

(4)

Many attributes available on the <class> mapping element are also available on <subclass> with the same usage: proxy, dynamic-update, dynamic-insert, select-before-update, persister, batch-size, lazy, entity-name, abstract. See Section 5.1.3, “class”.

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.

For information about inheritance mappings, see Chapter 9, Inheritance Mapping.

5.1.17. joined-subclass

Each subclass can also be mapped to its own table. This is called the table-per-subclass mapping strategy. An inherited state is retrieved by joining with the table of the superclass. To do this you use the <joined-subclass> element.

<joined-subclass
    name="className"                                  (1)
    table="tableName"                                 (2)
    extends="superclassName"                          (3)
    ...>                                              (4)

    <key ... />

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

name: The fully qualified class name of the subclass.

(2)

table (optional - defaults to the unqualified subclass name): The name of the subclass table.

(3)

extends (optional if the <joined-subclass> element is nested into its superclass mapping declaration): Specifies the name of a mapped class as the superclass for the subclass.

(4)

Many attributes available on the <class> mapping element are also available on <joined-subclass> with the same usage: schema, catalog, proxy, subselect, dynamic-update, dynamic-insert, select-before-update, persister, batch-size, lazy, entity-name, abstract, check, schema-action. See Section 5.1.3, “class”.

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>

For information about inheritance mappings, see Chapter 9, Inheritance Mapping.

5.1.18. union-subclass

A third option is to map only the concrete classes of an inheritance hierarchy to tables, (the table-per-concrete-class strategy) where each table defines all persistent state of the class, including inherited state. In NHibernate, it is not absolutely necessary to explicitly map such inheritance hierarchies. You can simply map each class with a separate <class> declaration. However, if you wish use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the <union-subclass> mapping.

<union-subclass
    name="className"                                  (1)
    table="tableName"                                 (2)
    extends="superclassName"                          (3)
    ...>                                              (4)

    <property ... />
    <properties ... />
    ...
</union-subclass>
(1)

name: The fully qualified class name of the subclass.

(2)

table (optional - defaults to the unqualified subclass name): The name of the subclass table.

(3)

extends (optional if the <union-subclass> element is nested into its superclass mapping declaration): Specifies the name of a mapped class as the superclass for the subclass.

(4)

Many attributes available on the <class> mapping element are also available on <union-subclass> with the same usage: schema, catalog, proxy, subselect, dynamic-update, dynamic-insert, select-before-update, persister, batch-size, lazy, entity-name, abstract, check. See Section 5.1.3, “class”.

No discriminator column or key column is required for this mapping strategy.

For information about inheritance mappings, see Chapter 9, Inheritance Mapping.

5.1.19. join

Using the <join> element, it is possible to map properties of one class to several tables, when there's a 1-to-1 relationship between the tables.

<join
    table="tableName"                            (1)
    schema="owner"                               (2)
    catalog="catalog"                            (3)
    fetch="join|select"                          (4)
    inverse="true|false"                         (5)
    optional="true|false"                        (6)
    subselect="SQL expression">                  (7)

    <key ... />

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

table: The name of the joined table.

(2)

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

(3)

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

(4)

fetch (optional - defaults to join): If set to join, the default, NHibernate will use an inner join to retrieve a <join> defined by a class or its superclasses and an outer join for a <join> defined by a subclass. If set to select then NHibernate will use a sequential select for a <join> defined on a subclass, which will be issued only if a row turns out to represent an instance of the subclass. Inner joins will still be used to retrieve a <join> defined by the class and its superclasses.

(5)

inverse (optional - defaults to false): If enabled, NHibernate will not try to insert or update the properties defined by this join.

(6)

optional (optional - defaults to false): If enabled, NHibernate will insert a row only if the properties defined by this join are non-null and will always use an outer join to retrieve the properties.

(7)

subselect (optional): Maps an immutable and read-only join to a database sub-select. This is useful if you want to have a view instead of a table. See Section 5.1.4, “subselect” for more information.

For example, the address information for a person can be mapped to a separate table (while preserving value type semantics for all properties):

<class name="Person" table="PERSON">
    <id name="id" column="PERSON_ID">...</id>

    <join table="ADDRESS">
        <key column="ADDRESS_ID"/>
        <property name="address"/>
        <property name="zip"/>
        <property name="country"/>
    </join>
    ...

This feature is often only useful for legacy data models, we recommend fewer tables than classes and a fine-grained domain model. However, it is useful for switching between inheritance mapping strategies in a single hierarchy, as explained later.

5.1.20. key

The <key> element has featured a few times within this guide. It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table. It also defines the foreign key in the joined table:

<key
        column="columnName"                      (1)
        on-delete="noaction|cascade"             (2)
        property-ref="propertyName"              (3)
        not-null="true|false"                    (4)
        update="true|false"                      (5)
        unique="true|false"                      (6)
        foreign-key="foreignKeyName"             (7)
/>
(1)

column: the name of the foreign key column. This can also be specified by nested <column> element(s).

(2)

on-delete (optional - defaults to noaction): specifies whether the foreign key constraint has database-level cascade delete enabled.

(3)

property-ref (optional): specifies that the foreign key refers to columns that are not the primary key of the original table. It is provided for legacy data.

(4)

not-null (optional): specifies that the foreign key columns are not nullable. This is implied whenever the foreign key is also part of the primary key.

(5)

update (optional): specifies that the foreign key should never be updated. This is implied whenever the foreign key is also part of the primary key.

(6)

unique (optional): specifies that the foreign key should have a unique constraint. This is implied whenever the foreign key is also the primary key.

(7)

foreign-key (optional): specifies the name of the foreign key constraint for DDL generation.

For systems where delete performance is important, we recommend that all keys should be defined on-delete="cascade". NHibernate uses a database-level ON CASCADE DELETE constraint, instead of many individual DELETE statements. Be aware that this feature bypasses NHibernate's usual optimistic locking strategy for versioned data.

The not-null and update attributes are useful when mapping an unidirectional one-to-many association. If you map an unidirectional one-to-many association to a non-nullable foreign key, you must declare the key column using <key not-null="true">.

5.1.21. column and formula elements

Mapping elements which accept a column attribute will alternatively accept a <column> subelement. Likewise, <formula> is an alternative to the formula attribute. For example:

<column
        name="columnName"
        length="N"
        precision="N"
        scale="N"
        not-null="true|false"
        unique="true|false"
        unique-key="multicolumnUniqueKeyName"
        index="indexName"
        sql-type="sqlTypeName"
        check="SQL expression"
        default="SQL expression"/>
<formula>SQL expression</formula>

Most of the attributes on column provide a means of tailoring the DDL during automatic schema generation. See Section 22.1.1, “Customizing the schema”.

The column and formula elements can even be combined within the same property or association mapping to express, for example, exotic join conditions.

<many-to-one name="HomeAddress" class="Address"
        insert="false" update="false">
    <column name="person_id" not-null="true" length="10"/>
    <formula>'MAILING'</formula>
</many-to-one>

5.1.22. map, set, list, bag

Collections are discussed in Chapter 6, Collection Mapping.

5.1.23. 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.1.24. any

There is one more type of property mapping. The <any> mapping element defines a polymorphic association to classes from multiple tables. This type of mapping requires more than one column. The first column contains the type of the associated entity. The remaining columns contain the identifier. It is impossible to specify a foreign key constraint for this kind of association. This is not the usual way of mapping polymorphic associations and you should use this only in special cases. For example, for audit logs, user session data, etc.

<any name="AnyEntity" id-type="long" meta-type="class">
    <column name="type"/>
    <column name="id"/>
</any>

The meta-type attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by id-type. If the meta-type is class, nothing else is required. The class full name will be persisted in the database as the type of the associated entity. On the other hand, if it is a basic type like int or char, you must specify the mapping from values to classes. Here is an example with string.

<any name="being" id-type="long" meta-type="string">
    <meta-value value="ANIMAL_TYPE" class="Animal"/>
    <meta-value value="HUMAN_TYPE" class="Human"/>
    <meta-value value="ALIEN_TYPE" class="Alien"/>
    <column name="type"/>
    <column name="id"/>
</any>

String types are a special case: they can be used without meta-values, in which case they will behave much like the class meta-type.

<any
    name="propertyName"                               (1)
    id-type="idTypeName"                              (2)
    meta-type="metaTypeName"                          (3)
    cascade="cascadeStyle"                            (4)
    access="field|property|className"                 (5)
    optimistic-lock="true|false"                      (6)
    lazy="true|false"                                 (7)
    update="true|false"                               (8)
    insert="true|false"                               (9)
    index="indexName">                                (10)

    <meta-value ... />
    <meta-value ... />
    ...
    <column ... />
    <column ... />
    ...
</any>
(1)

name: the property name.

(2)

id-type: the identifier type.

(3)

meta-type (optional - defaults to string): a type that is allowed for a discriminator mapping, or class.

(4)

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

(5)

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

(6)

optimistic-lock (optional - defaults to true): specifies that updates to this property either do or do not require acquisition of the optimistic lock. It defines whether a version increment should occur if this property is dirty.

(7)

lazy (optional - defaults to false): specifies that this property should be fetched lazily when the it is first accessed. For more informations, see lazy on property element.

(8)

update (optional - defaults to true): Do the mapped columns appear in SQL UPDATEs?

(9)

insert (optional - defaults to true): Do the mapped columns appear in SQL INSERTs?

(10)

index (optional): a logical name for an index for DDL generation. The column will be included in the index, along with other columns sharing the same index logical name. The actual index name depends on the dialect.

Do not confuse <meta-value> elements with <meta> elements. <meta> elements have no functionnal impact on <any>, see Section 5.8, “Meta data” for more information on them.

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 .NET 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.

The challenge is to map the .Net type system, and the developers' definition of entities and value types, to the SQL/database type system. The bridge between both systems is provided by NHibernate. For entities, <class>, <subclass> and so on are used. For value types we use <property>, <component>, etc., that usually have a type attribute. The value of this attribute is the name of a NHibernate mapping type. NHibernate provides a range of mappings for standard .Net value types out of the box. You can write your own mapping types and implement your own custom conversion strategies.

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 Columns for System.ValueType types can handle null values only if the entity property is properly typed with a Nullable<T>. Otherwise null will be replaced by the default value for the type when reading, and then will be overwritten by it when persisting the entity, potentially leading to phantom updates.

Table 5.3. System.ValueType Mapping Types

NHibernate Type.NET TypeDatabase TypeRemarks
AnsiCharSystem.CharDbType.AnsiStringFixedLength - 1 chartype="AnsiChar" must be specified.
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.
CurrencySystem.DecimalDbType.Currencytype="Currency" must be specified.
DateSystem.DateTimeDbType.Datetype="Date" must be specified.
DateTimeSystem.DateTimeDbType.DateTime / DbType.DateTime2(1) Default when no type attribute specified. Does no longer ignore fractional seconds since NHibernate v5.0.
DateTimeNoMsSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="DateTimeNoMs" must be specified. Ignores fractional seconds. Available since NHibernate v5.0.
DateTime2System.DateTimeDbType.DateTime2type="DateTime2" must be specified. Obsolete since NHibernate v5.0, use DateTime instead.
DateTimeOffsetSystem.DateTimeOffsetDbType.DateTimeOffsetDefault when no type attribute specified.
DbTimestampSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="DbTimestamp" must be specified. When used as a version field, uses the database's current time retrieved in dedicated queries, rather than the client's current time. In case of lack of database support, it falls back on the client's current time.
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.
LocalDateTimeSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="LocalDateTime" must be specified. Ensures the DateTimeKind is set to DateTimeKind.Local. Throws if set with a date having another kind. Does no longer ignore fractional seconds since NHibernate v5.0.
LocalDateTimeNoMsSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="LocalDateTimeNoMs" must be specified. Similar to LocalDateTime but ignores fractional seconds. Available since NHibernate v5.0.
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.
SByteSystem.SByteDbType.SByteDefault when no type attribute specified.
SingleSystem.SingleDbType.SingleDefault when no type attribute specified.
TicksSystem.DateTimeDbType.Int64type="Ticks" must be specified. This is the recommended way to "timestamp" a column, along with UtcTicks.
TimeSystem.DateTimeDbType.Timetype="Time" must be specified.
TimeAsTimeSpanSystem.TimeSpanDbType.Timetype="TimeAsTimeSpan" must be specified.
TimeSpanSystem.TimeSpanDbType.Int64Default when no type attribute specified.
TimestampSystem.DateTimeDbType.DateTime / DbType.DateTime2(1) Obsolete, its Timestamp alias will be remapped to DateTime in a future version.
TrueFalseSystem.BooleanDbType.AnsiStringFixedLength - 1 char either 'T' or 'F'type="TrueFalse" must be specified.
UInt16System.UInt16DbType.UInt16Default when no type attribute specified.
UInt32System.UInt32DbType.UInt32Default when no type attribute specified.
UInt64System.UInt64DbType.UInt64Default when no type attribute specified.
UtcDateTimeSystem.DateTimeDbType.DateTime / DbType.DateTime2(1) Ensures the DateTimeKind is set to DateTimeKind.Utc. Throws if set with a date having another kind. Does no longer ignore fractional seconds since NHibernate v5.0.
UtcDateTimeNoMsSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="UtcDateTimeNoMs" must be specified. Similar to UtcDateTime but ignores fractional seconds. Available since NHibernate v5.0.
UtcDbTimestampSystem.DateTimeDbType.DateTime / DbType.DateTime2(1)type="UtcDbTimestamp" must be specified. When used as a version field, uses the database's current UTC time retrieved in dedicated queries, rather than the client's current time. In case of lack of database support, it falls back on the client's current time.
UtcTicksSystem.DateTimeDbType.Int64type="UtcTicks" must be specified. This is the recommended way to "timestamp" a column, along with Ticks. Ensures the DateTimeKind is set to DateTimeKind.Utc. Throws if set with a date having another kind.
YesNoSystem.BooleanDbType.AnsiStringFixedLength - 1 char either 'Y' or 'N'type="YesNo" must be specified.
(1)

Since NHibernate v5.0 and if the dialect supports it, DbType.DateTime2 is used instead of DbType.DateTime. This may be disabled by setting sql_types.keep_datetime to true.

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.
UriSystem.UriDbType.StringDefault when no type attribute specified.

String types use by default .Net default string equality, which is case sensitive and culture insensitive. When a string type is used as an identifier, if the underlying database string equality semantic differs, it may cause issues. For example, loading a children collection by a string parent key stored in a case insensitive column may cause matching children having their parent key differing by the case to be ignored by NHibernate by default.

String types comparer can be set for matching the database or column behavior. To set the default comparer for all string types, affect by code a StringComparer to AbstractStringType.DefaultComparer static property. To set the comparer used only for a specific <property> or <id>, specify its type as a sub-element and supply IgnoreCase and/or ComparerCulture parameters.

<id name="Id" generator="assigned">
    <type name="string">
        <param name="ComparerCulture">en-US</param>   (1)
        <param name="IgnoreCase">true</param>         (2)
    </type>
</id>
(1)

IgnoreCase: true for case insensitive comparisons. Any other value will result in case sensitive comparisons.

(2)

ComparerCulture: Current for using the application current culture, Invariant for using the invariant culture, Ordinal for using ordinal comparison, or any valid culture name for using another culture. By default, ordinal comparisons are used.

If you have many properties to map with these parameters, consider using <typedef>. See Section 5.2.3, “Custom value types” for more information.

These settings should be used in order to match the database or column behavior. They are not taken into account by the hbm2ddl tool for generating the database schema. (In other words, it will not generate matching collate statements for SQL-Server.)

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.
XDocSystem.Xml.Linq.XDocumentDbType.XmlDefault when no type attribute specified. Entire field is read into memory.
XmlDocSystem.Xml.XmlDocumentDbType.XmlDefault when no type attribute specified. Entire field is read into memory.

NHibernate supports some additional type names for compatibility with Java's 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.

Default NHibernate types used when no type attribute is specified can be overridden by using the NHibernate.Type.TypeFactory.RegisterType static method before configuring and building session factories.

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 IEnhancedUserType, IUserVersionType, and IUserCollectionType interfaces provide support for more specialized uses. The later is to be used with collections, see Section 6.1, “Persistent Collections”.

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.

If you use a certain UserType very often, it may be useful to define a shorter name for it. You can do this using the <typedef> element. Typedefs assign a name to a custom type, and may also contain a list of default parameter values if the type is parameterized.

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

It is also possible to override the parameters supplied in a typedef on a case-by-case basis by using type parameters on the property mapping.

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.3. Mapping a class more than once

It is possible to provide more than one mapping for a particular persistent class. In this case, you must specify an entity name to disambiguate between instances of the two mapped entities. By default, the entity name is the same as the class name. NHibernate lets you specify the entity name when working with persistent objects, when writing queries, or when mapping associations to the named entity.

<class name="Contract" table="Contracts"
        entity-name="CurrentContract">
    ...
    <set name="History" inverse="true"
            order-by="effectiveEndDate desc">
        <key column="currentContractId"/>
        <one-to-many entity-name="HistoricalContract"/>
    </set>
</class>

<class name="Contract" table="ContractHistory"
        entity-name="HistoricalContract">
    ...
    <many-to-one name="CurrentContract"
            column="currentContractId"
            entity-name="CurrentContract"/>
</class>

Associations are now specified using entity-name instead of class.

5.4. SQL quoted identifiers

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

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

Quoting column identifiers is required if a table contains two columns differing only by case. Ensure you use consistent casing when quoting identifiers.

5.5. Modular mapping files

It is possible to define subclass and joined-subclass mappings in separate mapping documents, directly beneath hibernate-mapping. This allows you to extend a class hierarchy just by adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming a previously mapped superclass.

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

        <property name="name" type="string"/>
    </subclass>
</hibernate-mapping>

5.6. Generated Properties

Generated properties are properties which have their values generated by the database. Typically, NHibernate applications needed to Refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to NHibernate. Essentially, whenever NHibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values.

Properties marked as generated must additionally be non-insertable and non-updatable. Only versions, timestamps, and simple properties can be marked as generated.

never (the default) - means that the given property value is not generated within the database.

insert - states that the given property value is generated on insert, but is not regenerated on subsequent updates. Things like created-date would fall into this category. Note that even though version and timestamp properties can be marked as generated, this option is not available for them.

always - states that the property value is generated both on insert and on update.

5.7. Auxiliary Database Objects

Auxiliary database objects allow CREATE and DROP of arbitrary database objects. In conjunction with NHibernate's schema evolution tools, they have the ability to fully define a user schema within the NHibernate mapping files. Although designed specifically for creating and dropping things like triggers or stored procedures, any SQL command that can be run via a DbCommand.ExecuteNonQuery() method is valid (for example, ALTERs, INSERTS, etc.). There are essentially two modes for defining auxiliary database objects:

The first mode is to explicitly list the CREATE and DROP commands in the mapping file:

<nhibernate-mapping>
    ...
    <database-object>
        <create>CREATE TRIGGER my_trigger ...</create>
        <drop>DROP TRIGGER my_trigger</drop>
    </database-object>
</nhibernate-mapping>

The second mode is to supply a custom class that constructs the CREATE and DROP commands. This custom class must implement the NHibernate.Mapping.IAuxiliaryDatabaseObject interface.

<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition, MyAssembly"/>
    </database-object>
</hibernate-mapping>

You may also specify parameters to be passed to the database object:

<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition, MyAssembly">
            <param name="parameterName">parameterValue</param>
        </definition>
    </database-object>
</hibernate-mapping>

NHibernate will call IAuxiliaryDatabaseObject.SetParameterValues passing it a dictionary of parameter names and values.

Additionally, these database objects can be optionally scoped such that they only apply when certain dialects are used.

<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition"/>
        <dialect-scope name="NHibernate.Dialect.Oracle9iDialect"/>
        <dialect-scope name="NHibernate.Dialect.Oracle8iDialect"/>
    </database-object>
</hibernate-mapping>

5.8. Meta data

You may declare additional metadata in your mappings by using the meta element. This element can be added to the main mapping elements.

<meta
    attribute="metaName"                              (1)
    inherit="true|false"                              (2)
    >metaData</meta>
(1)

attribute: The name of the metadata.

(2)

inherit (optional - defaults to true): Whether the metadata is inherited by mapping sub-elements or not.

(3)

The text content of the meta element is its data.

The metadata can be retrieved at runtime from the Section 10.12, “Metadata API”.