首页 > 代码库 > NHibernate官方文档中文版--基础ORM(Basic O/R Mapping)

NHibernate官方文档中文版--基础ORM(Basic O/R Mapping)

映射声明

对象/关系映射在XML文件中配置。mapping文件这样设计是为了使它可读性强并且可修改。mapping语言是以对象为中心,意味着mapping是围绕着持久化类声明来建立的,而不是围绕数据表。

要注意的是,尽管很多NHibernate使用者选择手动定义XML文件,但是仍然有很多工具可以用来生成mapping文件,包括NHibernate.Mapping.Attributes 库和各种各样基于模板的代码生成工具(CodeSmith, MyGeneration)。

让我们用一个mapping的例子作为开始:

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

        <class name="Cat" table="CATS" discriminator-value=http://www.mamicode.com/"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=http://www.mamicode.com/"D">
                        <property name="Name" type="String"/>
                </subclass>
        </class>

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

</hibernate-mapping>

我们现在讨论mapping文件中的内容。我们将只会描述NHibernate在运行时使用的文档中的标签和特性。mapping文件也包含一些额外的可选的特性和标签,这些特性和标签会影响表结构导出工具(schema export tool)导出的数据库的表结构(database schemas)。(例如not-null特性)。

XML名称空间

所有的XMLmapping应该声明XML名称空间。规定的XML结构定义(schema definition)可以在NHibernate发行版中的src\nhibernate-mapping.xsd 中找到。

小建议:想要启用mapping和配置文件的智能感知功能,需要将相应的.xsd文件作为你解决方案中所有项目的一部分(生成操作可以是‘none’)或者作为“solution files”,或者放在你的“lib”文件夹中,然后将它添加到你的XML文件的schemas属性中。你可以在<VS installation directory>\Xml\Schemas中复制它,要注意你可能得将不同版本的xsd对应不同版本的NHibernate。

hibernate-mapping

这个标签有很多可选的特性。schema特性定义了对应表的数据库表空间。如果指定了相应的表空间,那么数据表名称就会被限定在给定的表空间。如果这个置空,就不会限定表空间。default-cascade 特性定义了没有详细指定级联方式的属性和集合的级联方式。默认情况下,auto-import 特性让我们在查询语句中使用不限定表空间的类名。assembly 和 namespace特性定义了持久化类位于哪个程序集中,在哪个名称空间中声明。

           <hibernate-mapping                         (1)
         schema="schemaName"                          (2)
         default-cascade="none|save-update"           (3)
         auto-import="true|false"                     (4)
         assembly="Eg"                                (5)
         namespace="Eg"                               (6)
         default-access="field|property|field.camecase(7)..."
         default-lazy="true|false"
 />

(1) schema (可选): 数据库表空间的名称。

(2) default-cascade (可选 - 默认 none):  默认的级联方式。

(3) auto-import (可选 - 默认true):  定义是否可以在查询语句中使用非限定表空间的类名(在mapping文件中定义的类)。

(4)(5) assembly and namespace(可选):  指定非限定表空间的类所在的程序集和名称空间。

(6) default-access (可选- 默认 property): NHibernate获得属性值的方式

(7) default-lazy (可选- 默认 true):如果设置成false,懒加载就会被禁用

如果你不使用assembly和namespace特性,你就得使用完整的类名,包括程序集和名称空间的名称。

如果你有两个持久化类使用了相同的(未限定表空间的)名字,你应该将auto-import设置成false。如果你试图将两个类设置成相同的名称,那么NHibernate会抛出异常。

你可以使用class来定义一个持久化类:

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

(1) name: 持久化类(或者接口)的全限定名。

(2) table(optional - 默认是非限定的类名): 对应的数据库表名。

(3) discriminator-value (optional - 默认是类名):  一个用于区分不同的子类的值,在多态行为时使用。可以设置为null和not null。

(4) mutable (optional, 默认是true): 指定该类的实例可变(不可变)。

(5) schema (optional): 覆盖在根<hibernate-mapping> 标签中指定的表空间名字

(6) proxy (optional): Specifies an interface to use for lazy initializing proxies. You may specify the name of the class itself. 指定一个接口,在延迟装载时作为代理使用。你可以在这里使用该类自己的名字。

(7) dynamic-update (optional, defaults to false): 指定用于UPDATE 的SQL将会在运行时动态生成,并且只更新那些改变过的字段。

(8) dynamic-insert (optional, defaults to false): 指定用于INSERT的SQL将会在运行时动态生成,并且只包含那些非空字段。

(9) select-before-update (optional, defaults to false): 指定NHibernate是否需要执行UPDATE操作,除非它确定对象真的被修改了,不然就不会执行。在一些特定的情况下(实际上仅仅当瞬时态对象要执行update()而被关联到一个新的session的时候),这意味着NHibernate在执行UPDATE之前会执行一个额外的SELECT的SQL语句操作来判断是不是真的需要进行UPDATE。

(10) polymorphism (optional, defaults to implicit):  指定是隐式还是显式的使用查询多态。

(11) where (optional)  指定一个附加的SQL WHERE 条件,在抓取这个类的对象时会一直增加这个条件。

(12) persister (optional):  指定一个自定义的IClassPersister.

(13) batch-size (optional, defaults to 1) 指定通过主键获得实体方式的批量插入量

(14) optimistic-lock (optional, defaults to version): 指定乐观锁策略。

(15) lazy (optional): 如果设置成lazy="false"懒加载会被完全关闭。

(16) abstract (optional):  用来在<union-subclass>继承中标记抽象父类

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

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

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

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

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

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

若指明的持久化类实际上是一个接口,也可以被完美地接受。其后你可以用 <subclass> 来指定该接口的实际实现类名。你可以持久化任何static(静态的)内部类。记得应该使用标准的类名格式,就是说比如:Eg.Foo+Bar 。这是因为HQL解析器的限制,在NHibernate 1.0版本中,在查询中不能使用内部类。

任何对不可变类的修改操作,mutable="false",都不会被持久化。这可以让NHibernate做一些小小的性能优化。

可选的proxy属性可以允许延迟加载类的持久化实例。NHibernate开始会返回实现了这个命名接口或者子类(通过的 Castle.DynamicProxy)。当代理的某个方法被实际调用的时候,真实的持久化对象才会被装载。参见下面的“用于延迟加载的代理”。

Implicit (隐式)的多态是指,如果查询中给出的是任何超类、该类实现的接口或者该类的名字,都会返回这个类的实例;如果查询中给出的是子类的名字,则会返回子类的实例。Explicit (显式)的多态是指,只有在查询中给出的明确是该类的名字时才会返回这个类的实例;同时只有当在这个 <class> 的定义中作为 <subclass> 或者 <joined-subclass> 出现的子类,才会可能返回。 大多数情况下,默认的polymorphism="implicit"都是合适的。 显式的多态在有两个不同的类映射到同一个表的时候很有用。(允许一个“轻型”的类,只包含部分表字段)。

persister属性可以让你定制这个类使用的持久化策略。你可以指定你自己实现的NHibernate.Persister.EntityPersister的子类,你甚至可以完全从头开始编写一个NHibernate.Persister.IClassPersister接口的实现,可能是用储存过程调用、序列化到文件或者LDAP数据库来实现的。参阅NHibernate.DomainModel.CustomPersister,这是一个简单的例子(“持久化”到一个Hashtable)。

请注意dynamic-update和dynamic-insert的设置并不会继承到子类,所以在<subclass>或者<joined-subclass>元素中可能需要再次设置。这些设置是否能够提高效率要视情形而定。请用你的智慧决定是否使用。

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

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

使用select-before-update 通常会降低性能。但是这种方式能够有效地防止不必要的数据库更新。

如果你使用了你就可以选择一种乐观锁的策略:

  • version check the version/timestamp columns  检查version/timestamp 行

  • all check all columns 检查所有行

  • dirty check the changed columns 检查改变的行

  • none do not use optimistic locking 不适用乐观锁

  • 我们强烈建议你使用NHibernate的乐观锁功能的时候使用version/timestamp 。考虑到性能问题,这个是最佳并且唯一的方案来正确地处理在session(例如,当使用ISession.Update() )之外的修改操作。要记住,version或者timestamp属性永远不能为null,无论是哪种unsaved-value 方案,或者实体将要变成游离态。

从NHibernate 1.2.0开始,version的是从1开始,而不是像之前的版本那样从0开始。这个目的是为了让unsaved-value设置成04545485458478¥#%……#

子查询

一个其他的映射类的方式是映射一个查询。为了达到这个目的,我们可以使用<subselect>标签,这个标签是独立于<class>, <subclass>, <joined-subclass> 和 <union-subclass>的。subselect标签中的内容是一个SQL查询:

<subselect>
    SELECT cat.ID, cat.NAME, cat.SEX, cat.MATE FROM cat
</subselect>

一般来说,当使用subselect来mapping一个查询的时候,你会将类标记成不变的(mutable="false"),除非你使用了自定义的SQL来完成增删改操作。

其次,强制同步受到查询影响的数据表是有意义的,可以使用一个或者多个<synchronize> :

<subselect>
    SELECT cat.ID, cat.NAME, cat.SEX, cat.MATE FROM cat
</subselect>
<syncronize table="cat"/>

Id

被映射的类必须声明对应数据库表主键字段。大多数类有一个属性,为每一个实例包含唯一的标识。 <id> 标签定义了该属性到数据库表主键字段的映射。

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

        <generator class="generatorClass"/>
</id>

(1)name (可选): 标识属性的名字。

(2)type (可选):标识NHibernate类型的名字

(3)column (可选- 默认是这个属性的名称):主键字段的名字

(4)unsaved-value (可选- 默认是 "sensible" ): 一个特定的标识属性值,用来标志该实例是刚刚创建的,尚未保存。这可以把这种 实例和从以前的session中装载过(可能又做过修改--译者注)但未再次持久化的实例区分开来。

(5)access (可选- 默认值是property): NHibernate用来访问属性值的策略

如果name属性不存在,会认为这个类没有标识属性。

unsaved-value 属性在NHibernate 1.0中基本不需要。

还有一个另外的<composite-id>声明可以访问旧式的多主键数据。我们强烈不鼓励使用这种方式。

Id生成器

必须要有一个生成器,用来为该持久化类的实例生成唯一的标识。这个生成器可以使用<generator>子标签来声明。如果这个生成器实例需要某些配置值或者初始化参数,用 <param>元素来传递。

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

如果没有指定参数,就可以直接在<id> 标签中使用一个generator 特性来声明一个生成器,就像下面的这样:

<id name="Id" type="Int64" column="uid" unsaved-value=http://www.mamicode.com/"0" generator="native" />

所有的生成器实现NHibernate.Id.IIdentifierGenerator接口。这是一个非常简单的接口;某些应用程序可以选择提供他们自己特定的实现。当然,NHibernate提供了很多内置的实现。下面是一些内置生成器的快捷名字:

increment

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

仅在没有其他进程往同一张数据表中插入数据的时候生成独一无二的整型标识符。不要在一个集群中使用这种生成方式。

identity

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

对DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL的内置标识字段提供支持。返回的标识符是 Int64, Int32 或者 Int16类型的。

sequence

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

对DB2,MySQL, PostgreSQL, Oracle的内置标识字段提供支持。返回的标识符是Int64 Int32  或者 Int16类型的。

hilo

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

You can use the "where" parameter to specify the row to use in a table. This is useful if you want to use a single tabel for your identifiers, with different rows for each table.

使用一个高/低位算法来高效的生成Int64, Int32 或者 Int16类型的标识符。给定一个表和字 段(默认分别是hibernate_unique_key 和next)作为高位值得来源。高/低位算法生成的标识符只在一个特定的数据库中是唯一的。

seqhilo

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

使用一个高/低位算法来高效的生成Int64, Int32 或者 Int16类型的标识符,给定一个数据库 序列(sequence)的名字。

uuid.hex

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

用一个System.Guid和它的ToString(string format)方法生成字符串类型的标识符。字符串的长度取决于 format的配置。

uuid.string

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

用一个新的System.Guid产生一个byte[] ,把它转换成字符串。

guid

uses a new System.Guid as the identifier.

用一个新的System.Guid 作为标识符。

guid.comb

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

用Jimmy Nilsson在文章http://www.informit.com/articles/article.asp?p=25862中描述的算 法产生一个新的System.Guid。

native

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

根据底层数据库的能力选择 identity, sequence 或者 hilo中的一个。

assigned

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

让应用程序在save()之前为对象分配一个标示符。

foreign

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

使用另外一个相关联的对象的标识符。和<one-to-one>联合一起使用。

Hi/Lo算法

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

hilo 和 seqhilo生成器给出了两种hi/lo算法的实现,这是一种很令人满意的标识符生成算法。第一种实现需要一个“特殊”的数据库表来保存下一个可用的“hi”值。第二种实现使用一个Oracle风格的序列(在被支持的情况下)。

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

很不幸,你在为NHibernate自行提供Connection时无法使用hilo 。Hibernate必须能够在一个新的事务中得到一个"hi"值。

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

UUID十六进制算法

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

UUID是通过调用Guid.NewGuid().ToString(format)产生的。format值的设置请参考MSDN文档。默认的seperator很少也不应该被改变。format决定是否配置好的seperator 能替换format使用的默认seperator。

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.

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.

UUID是通过调用 Guid.NewGuid().ToByteArray() 并且把 byte[]转换成char[],char[] 做为一个16个字符组成的字符串返回。

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.

guid 标识符通过调用Guid.NewGuid()产生。 为了提升Guids在MS SQL中作为主键,外键和索引的一部分时的性能,可以使用guid.comb。在别的数据库中使用guid.comb的好处是支持非标准的GUID。

标识符字段和序列

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.

对于内部支持标识字段的数据库(DB2,MySQL,Sybase,MS SQL),你可以使用identity关键字生成。对于内部支持序列的数据库(DB2,Oracle, PostgreSQL),你可以使用sequence风格的关键字生成。这两种方式对于插入一个新的对象都需要两次SQL查询。

<id name="Id" type="Int64" column="uid">
        <generator class="sequence">
                <param name="sequence">uid_sequence</param>
        </generator>
</id>
<id name="Id" type="Int64" column="uid" unsaved-value=http://www.mamicode.com/"0">
        <generator class="identity"/>
</id>

对于跨平台开发,native策略会从identity, sequence 和hilo中进行选择,取决于底层数据库的支持能力。

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

由程序分配的标识符

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

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

如果你需要应用程序分配一个标示符(而非NHibernate来生成它们),你可以使用assigned生成器。这种特殊的生成器会使用已经分配给对象的标识符属性的标识符值。用这种特性来分配商业行为的关键字要特别小心(基本上总是一种可怕的设计决定)。

因为其继承天性,使用这种生成器策略的实体不能通过ISession的SaveOrUpdate()方法保存。作为替代,你应该明确告知NHibernate是应该被save还是update,分别调用ISession的Save()或Update()方法。

强化版标识符生成器

Starting with NHibernate release 3.3.0, there are 2 new generators which represent a re-thinking of 2 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, starting in 3.3.x. However, they are included in the current releases and can be referenced by FQN.

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.

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

  • prefer_sequence_per_entity (optional - defaults to false): should we create separate sequence for each entity that share current generator based on its name?

  • sequence_per_entity_suffix (optional - defaults to _SEQ): suffix added to the name of a dedicated sequence.

  • optimizer (optional - defaults to none): See Section 5.1.5.8.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.

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

  • 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 ??): See Section 5.1.5.8.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.8, “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.

联合ID

<composite-id
        name="PropertyName"
        class="ClassName"
        unsaved-value=http://www.mamicode.com/"any|none"
        access="field|property|nosetter|ClassName">

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

如果表使用联合主键,你可以把类的多个属性组合成为标识符属性。<composite-id>元素接受<key-property>属性映射和<key-many-to-one>属性映射作为子元素。

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>

你的持久化类必须重载Equals()和HashCode()方法,来实现组合的标识符判断等价.也必须实现Serializable接口   不幸的是,这种组合关键字的方法意味着一个持久化类是它自己的标识。除了对象自己之外,没有什么方便的“把手”可用。你必须自己初始化持久化类的实例,在使用组合关键字Load()持久化状态之前,必须填充他的联合属性。我们会在Section 7.4, “Components as composite identifiers”. 中说明一种更加方便的方法,把联合标识实现为一个独立的类,下面描述的属性只对这种备用方法有效:

(1)  name (可选): 一个组件类型,持有联合标识(参见下一节)。

(2)  class (可选 - 默认为通过反射(reflection)得到的属性类型): 作为联合标识的组件类名(参见下一节)。

(3)  unsaved-value (可选 - 默认为 none): 假如被设置为any的值,就表示新创建,尚未被持久化的实例将持有的值。

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 will describe a much more convenient approach where the composite identifier is implemented as a saparate class in Section 7.4, “Components as composite identifiers”. The attributes described below apply only to this alternative approach:

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

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

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

识别器

在"一棵对象继承树对应一个表"的mapping策略中,<discriminator>元素是必需的,它声明了表的识别器字段。识别器字段包含标志值,用于告知持久化层应该为某个特定的行创建哪一个子类的实例。只能使用如下受到限制的一些类型:String, Char, Int32, Byte, Int16, Boolean, YesNo, TrueFalse.

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

(1)  column (可选 - 默认为 class) 识别器字段的名字

(2)  type (可选 - 默认为 String) 一个NHibernate字段类型的名字

(3)  force (可选 - 默认为 false) "强制"NHibernate指定允许的识别器值,就算取得的所有实例都是根类的。

(4)  insert (可选 - 默认为 true) 当识别器是被映射的组件的标识符的一部分时设置为false。

(5)  formula (可选) an arbitrary SQL expression that is executed when a type has to be evaluated. Allows content-based discrimination. 当一个类型需要被推断的时候执行的一个任意的SQL表达式。允许基于内容的识别。

标识器字段的实际值是根据<class> 和<subclass>元素的discriminator-value得来。

force 特性(仅仅)在表中包含额外的没有映射到持久化对象的识别字段的时候有用。这种情形并不常见。

通过使用formula 特性,你可以声明一个任意的SQL语句用来获得某行的类型。

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

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

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

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

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

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

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

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

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

版本(可选)

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

<version>标签是可选的,表示这个数据表包含的数据是划分版本的。如果你想要使用长时间事务的时候非常有用(见下文)。

<version
        column="version_column"                            (1)
        name="PropertyName"                                (2)
        type="typename"                                    (3)
        access="field|property|nosetter|ClassName"         (4)
        unsaved-value=http://www.mamicode.com/"null|negative|undefined|value"      (5)
        generated="never|always"                           (6)
/>

(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.NHibernate获得版本字段值的方法。

(5)unsaved-value (optional - defaults to a "sensible" value): A version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session. (undefined specifies that the identifier property value should be used.)一个版本属性值,表示一个实体是刚刚实例化的(未保存),将它和在之前的session中保存或者加载的持久化实例区分开来。(undefined 说明了这个标识符属性值应该被使用)

(6)generated (optional - defaults to never): Specifies that this version property value is actually generated by the database. See the discussion of Section 5.5, “Generated Properties”.说明了这个版本属性值是由数据库生成的。可以参见Section 5.5, “Generated Properties”的讨论。

版本数字可以是Int64, Int32, Int16, Ticks, Timestamp, or TimeSpan (或者他们对应的可空值类型)类型。

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

时间戳(可选)

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>标签表明这个数据表包含时间戳数据。时间戳可以是版本的一个替代品。时间戳是一种不太安全乐观锁的实现。然而,有些时候应用程序会用其他方式使用时间戳。

<timestamp
        column="timestamp_column"           (1)
        name="PropertyName"                 (2)
        access="field|property|nosetter|Clas(3)sName"
        unsaved-value=http://www.mamicode.com/"null|undefined|value"(4)
        generated="never|always"            (5)
/>

(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..NET的DateTime 类型的属性字段名称。

(3)access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.NHibernate获得时间戳字段值的方法。

(4)unsaved-value (optional - defaults to null): A timestamp property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session. (undefined specifies that the identifier property value should be used.)一个时间戳属性值,表示一个实体是刚刚实例化的(未保存),将它和在之前的session中保存或者加载的持久化实例区分开来。(undefined 说明了这个标识符属性值应该被使用)

(5)generated (optional - defaults to never): Specifies that this timestamp property value is actually generated by the database. See the discussion of Section 5.5, “Generated Properties”.说明了这个时间戳属性值是由数据库生成的。可以参见Section 5.5, “Generated Properties”的讨论。

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

注意,<timestamp> 和<version type="timestamp">是相同的。

属性

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

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

(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.指向NHibernate类型的名称

(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.指定被映射的字段是否被包含在SQL 的UPDATE或者INSERT声明中。将二者都设置成false会

(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.一个定义了一个计算后的属性的SQL语句。这个计算后的属性并没有对应的映射字段。

(6)access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.NHibernate用来获取属性值的策略。

(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.定义这个属性的更新是否需要获取乐观锁。用其他的话说就是,当这个属性dirty之后要不要变成新的版本。

(8)generated (optional - defaults to never): Specifies that this property value is actually generated by the database. See the discussion of Section 5.5, “Generated Properties”.指定这个属性值实际上是由数据库生成的。可以参考Section 5.5, “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 overriden in a specific query. Values for lazy properties are loaded when any lazy property of the object is accessed.指定这个属性是不是懒加载。一个懒加载的属性在实体被初始化加载的时候是不会被加载的,除非关联模式被相应的特定查询重写。当这个实体的懒加载属性被访问的时候,懒加载属性的值才会被加载。

typename could be:

类型名称可以是:

  • The name of a NHibernate basic type (eg. Int32, String, Char, DateTime, Timestamp, Single, Byte[], Object, ...). NHibernate的基础类型名称(例如Int32, String, Char, DateTime, Timestamp, Single, Byte[], Object,等

  • The name of a .NET type with a default basic type (eg. System.Int16, System.Single, System.Char, System.String, System.DateTime, System.Byte[], ...). .NET 基础类型名称(例如System.Int16, System.Single, System.Char, System.String, System.DateTime, System.Byte[], 等

  • The name of an enumeration type (eg. Eg.Color, Eg). 枚举类型(例如Eg.Color

  • The name of a serializable .NET type. 可序列化.NET类型名称。

  • The class name of a custom type (eg. Illflow.Type.MyCustomType). 自定义类型名称(例如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 基础类型之外的类型你必须指定完整的程序集限定名称(除非你在<hibernate-mapping>标签中设置了assemblynamespace 特性)。

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

NHibernate 支持.NET 2.0 的可空数据类型。这些类型在代码内几乎都和原本的对应可空类型一样。例如,Nullable<Int32>可以使用type="Int32" 或者 type="System.Int32"来配置映射。

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

如果你没有指定类型,NHibernate会使用反射来反推出对应的属性类型。NHibernate会按照规则2,3,4的顺序尝试着推测出getter返回类型的名字。然而,这并不足以应付所有情况。在一些情况下,你仍然需要指定type特性(例如,要区分NHibernateUtil.DateTimeNHibernateUtil.Timestamp或者其他的自定义类型的时候)。

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.

access 特性能够让你控制NHibernate在运行时获得属性值的方式。access 应该是字符形式的access-strategy.naming-strategy。.naming-strategy并不是必须的。

表:access策略

Access 策略名称

介绍

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.
默认的实现模式。NHibernate使用属性的get/set 方法。使用这种方式的话,就不能使用任何的命名规则,因为name特性的值就是属性的名称。
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.
NHibernate会直接访问字段。NHibernate使用name特性的值作为字段的名称。当在属性的getter和setter包含了额外的动作,并且你不希望NHibernate在扩充或者获取这个对象的时候触发。如果你希望你的API的使用者使用HQL的时候使用的是属性的名称而不是字段,就要使用这个名称策略。
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.
在为属性赋值或者获得属性的值的时候NHibernate会直接访问字段。当你的API使用者不能直接改变属性值,也就是说,一个属性仅仅暴露get访问器的时候,有用。一个名称策略在NHibernate使用name特性作为属性名称并且还需要知道字段名称的时候是需要的。
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).
如果NHibernate

表:名称策略

名称策略名称

介绍

camelcase

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

name特性转化成驼峰命名方式来查找字段。例如<property name="FooBar" ... >使用字段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.

name特性转化成驼峰命名方式并切加上下划线来查找字段。例如<property name="FooBar" ... >使用字段_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.

name特性转化成驼峰命名方式并且以m为前缀,然后加上下划线来查找字段。例如<property name="FooBar" ... >使用字段m_fooBar

lowercase

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

name特性转化成了小写字符来查找字段。例如<property name="FooBar" ... >使用字段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.

name特性转化成了小写字符并且加上下划线。例如<property name="FooBar" ... >使用字段_foobar

pascalcase-underscore

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

name特性加上下划线来查找字段。例如<property name="FooBar" ... >使用字段_ooBar。

pascalcase-m

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

name特性以m作为前缀来查找字段。例如<property name="FooBar" ... >使用字段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.

name特性以m作为前缀,然后加上下划线来查找字段。例如<property name="FooBar" ... >使用字段m_FooBar。

多对一关系

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

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

(1)name: The name of the property.

(2)column (optional): The name of the column.

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

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

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

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

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

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

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

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

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

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

The fetch attribute accepts two different values:

  • join Fetch the association using an outer join
  • select Fetch the association using a separate query

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

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

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

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

Then the mapping for OrderItem might use:

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

This is certainly not encouraged, however.

一对一关系

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|(3)all-delete-orphan"
        constrained="true|false"                           (4)
        fetch="join|select"                                (5)
        property-ref="PropertyNameFromAssociatedClass"     (6)
        access="field|property|nosetter|ClassName"         (7)
/>

(1)name: The name of the property.

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

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

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

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

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

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

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

  • primary key associations

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

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

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

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

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

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

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

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

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

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

自然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.

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

组件,dynamic组件

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

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

(1)name: The name of the property.

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

(3)insert: Do the mapped columns appear in SQL INSERTs?

(4)update: Do the mapped columns appear in SQL UPDATEs?

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

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

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

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

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

属性

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: do the mapped columns appear in SQL INSERTs?

(3)update: 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.

子类

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

<subclass
        name="ClassName"                              (1)
        discriminator-value=http://www.mamicode.com/"discriminator_value"     (2)
        proxy="ProxyInterface"                        (3)
        lazy="true|false"                             (4)
        dynamic-update="true|false"
        dynamic-insert="true|false">

        <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 distiguishes individual subclasses.

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

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

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

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

join方式关联的子类

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

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

        <key .... >

        <property .... />
        <properties .... />
        .....
</joined-subclass>

(1)name: The fully qualified class name of the subclass.

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

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

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

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

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

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

</hibernate-mapping>

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

union方式关联的子类

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)
        proxy="ProxyInterface"              (3)
        lazy="true|false"                   (4)
        dynamic-update="true|false"
        dynamic-insert="true|false"
        schema="schema"
        catalog="catalog"
        extends="SuperclassName"
        abstract="true|false"
        persister="ClassName"
        subselect="SQL expression"
        entity-name="EntityName"
        node="element-name">

        <property .... />
        <properties .... />
        .....
</union-subclass>

(1)name: The fully qualified class name of the subclass.

(2)table: The name of the subclass table.

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

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

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

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

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)
        fetch="join|select"                      (3)
        inverse="true|false"                     (4)
        optional="true|false">                   (5)

        <key ... />

        <property ... />
        ...
</join>

(1)table: The name of the joined table.

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

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

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

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

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.

map, set, list, bag

Collections are discussed later.

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.

NHibernate 的类型

实体和值

想要明白各种关于持久化服务的.NET 语言级别对象,我们需要把他们区分成以下两种类型:

实体和其他与实体关联的对象独立。和实体相反,普通的.NET模型的关联会被GC回收。实体必须被显示地保存和删除(除了父类的级联保存和删除)。这个和依赖可获得性(reachability)来持久化的ODMG模型对象不同——并且相应的更接近在大系统中使用应用程序对象的方式。实体支持循环和共享的引用。它们也是有版本的。

实体的持久化状态包括了对其他实体的引用和值类型实例,值和基类,集合,组件和特定的不变对象。和实体不同,值类型(尤其是集合和组件)依赖可获得性(reachability)来进行持久化和删除。因为值类型对象(和基类)的持久化和删除都通过他们包含的实体,因此他们不需要独立的版本信息。值类型没有独立的标识符,因此他们不能够被两个实体或者集合共享。

对于.NET的可空类型(例如,不继承自System.ValueType)所有的NHibernate类型,除了集合,都支持null语法。

到这里位置,我们使用“持久化类”来指实体。我们将会继续这么做。严格来说,并不是所有的用户自定义的包含持久化状态的类都是实体。组件是一个包含值类型语法的自定义类型。

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.

基础值类型

基础值类型主要分成三类——System.ValueType 类型, System.Object 类型, 和大实体的 System.Object 类型。和.NET类型一样,System.ValueType 的值类型不能保存null值,而System.Object 类型可以为null。

Nhibernate支持一线额外的类型名称来兼容Java的Hibernate()type="integer"或者type="int"都会映射到Int32 的NHibernate类型,type="short"会映射到Int16的NHibernate类型。想要查阅所有的转化规则,你可以看源码中NHibernate.Type.TypeFactory类的静态构造函数。

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

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.

自定义值类型

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

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

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

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

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

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

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

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

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.

任意类型mapping

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

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

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

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

(1)name: the property name.

(2)id-type: the identifier type.

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

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

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

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

SQL引用标识符

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

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

模块mapping文件

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

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

生成的属性

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-updateable. Only Section 5.1.8, “version (optional)”, Section 5.1.9, “timestamp (optional)”, and Section 5.1.10, “property” 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 Section 5.1.8, “version (optional)” and Section 5.1.9, “timestamp (optional)” properties can be marked as generated, this option is not available there...

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

辅助的数据库对象

Allows CREATE and DROP of arbitrary database objects, in conjunction with NHibernate‘s schema evolution tools, to provide 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, really any SQL command that can be run via a IDbCommand.ExecuteNonQuery() method is valid here (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 out 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 which knows how to construct 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>

NHibernate官方文档中文版--基础ORM(Basic O/R Mapping)