日期:2009-01-07  浏览次数:20380 次

nh通过类映射文件将数据表与类关联起来. 由类对应表, 属性对应列. 这样我们才能把对象转为表记录, 把表记录转为对象.

这里以一个Products表为例, 来说明类映射文件的一些细节.

先来看看Product对象(在基于OO的设计概念中,是先设计对象的哦~), 这个类比较简单, 只有一些属性.

class Product() {
   product Product() {
}

#region O/R Mapping Fields.

private int productId; // 产品Id
public int ProductId
{
    get { return productId; }
    set { productId = value; }
}

private string name; // 名称
public string Name
{
    get { return name; }
    set { name = value; }
}

private string spec; // 规格
public string Spec
{
    get { return spec; }
    set { spec = value; }
}

private decimal unitPrice; // 单价
public decimal UnitPrice
{
    get { return unitPrice; }
    set { unitPrice = value; }
}

private DateTime updated; // 更新时间
public DateTime Updated
{
    get { return updated; }
    set { updated = value; }
}

#endregion
}

相应的Products表定义如下:

product_id int32 not null primary_key identity(1,1),
name varchar(50) not null,
spec varchar(100),
unit_price money,
updated datetime

现在可以建立Product的映射文件了.

<class name="Product, AssemblyName", table="Products">
    // 指定类名为Product, 数据表为Products.

    <id name="ProductId", column="product_id", type="Int32" unsaved="0">
      <generator class="identity"/>
   </id>
    // 指定一个id, 在数据表中就是主键, 这个非常重要, nh就是通过id来判断对象的唯一性的.
    // 在这里id名称是类的一个属性, 为ProductId, 对应的列是product_id.
    // unsaved指定对象为持久化时的值, 如果id的值与之相等, 那nh就认为这个对象是从为持久化过的.
    // generator指定一个id的产生器, 这里使用的是identity, 也即由数据库产生, 如果要自己产生, 那应使用assigned.

   <property name="Name" column="name" type="String"/>
   <property name="Spec" column="spec" type="String(100)"/>
   <property name="UnitPrice" column="unit_price" type="Decimal"/>
   <property name="Updated" column="updated" type="DateTime"/>
    // property用于将属性和列名一一关联起来. name指定属性名; column指定类名;
    // type指定类型, 如果省略type, nh就通过属生的类型来决定, 建议还是明确指定为好.
    // 注意: 这里指定的类型是nh中定义的类型, 而不是.net内置的类型!
</class>

持久化操作

// 先建立一个Product对象.
Product p = new Product();
p.Name = "test";
p.Spec = "test spec";
p.UnitPrice = 10.5;
p.Updated = DateTime.Now;

Configuration cfg = new Configuartion();
cfg.AddXMLFile( "product.hbm.XML" ); // 加入映射文件.

// 创建会话工厂, 一般来说应该使用一个单例对象来封装会话工厂.
ISessionFactory sf = cfg.BuildSessionFactory();

// 打开一个会话.
ISession s = sf.OpenSession();

// 保存Product对象到数据库.
s.Save( p );

// 通过已知id载入Product对象
Product p2 = s.Load( typeof(Product), p.ProductId );
p2.Name = "update";
p2.Spec = "update spec";

// 更新Product对象.
s.Update( p2 );

// 删除Product对象
s.Delete( p2 );