1. 学习目的
学习Nhibernate基础知识。掌握Nhibernate的配置方法,实现对单表的简单操作,如:创建表,查询,添加,删除,修改。
2. 开发环境+前期准备
开发环境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition
前期准备: Nhibernate框架,我用的目前最新版NHibernate-1.2.0.CR1, 下载地址: http://downloads.sourceforge.net/nhibernate/NHibernate-1.2.0.CR1.msi?modtime=1172161735&big_mirror=0
3. 开发步骤:
1).双击下载下来的NHibernate-1.2.0.CR1.msi,将其安装到某个目录,我的目录为: E:\download project\orm\nhibernate.,打开该目录,即可以看到bin,doc,src三个子目录,分别为Realse好的dll或者exe目录,文档说明目录,和源程序目录.
2).打开visual studio 2005,创建类库项目NhibernateSample1
3).在解决方案管理其中,右键点击引用-添加引用,在选项卡种选择浏览,设定查找范围为:E:\download project\orm\nhibernate\bin,添加对Nhibernate.dll,log4net.dll, Iesi.Collections, HashCodeProvider四个dll的引用.
4).打开SQL Server Management Studio,创建数据库nhibernate。
5).在解决方案管理器中添加hibernate.cfg.xml文件。将下面代码粘贴到此文件:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<!-- properties -->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=127.0.0.1;initial catalog=nhibernate;uid=sa;pwd=123;</property>
<property name="show_sql">false</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<!-- mapping files -->
<mapping assembly="NhibernateSample1" />
</session-factory>
</hibernate-configuration>

该文件是Nhibernate的配置文件,其中connection.connection_string为数据库连接字符串,Dialect项因为我用的是SQL2005,所以为:MsSql2005Dialect注意:<mapping assembly=”NhibernateSample1”/>表示映射NhibernateSample1程序集下的所有类,所以以后不要需要Configuration.AddClass(..)了;
6).添加类文件:User.cs,添加代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace NhibernateSample1


{
public class User

{
private int _id;
private string _name;
private string _pwd;

/**//// <summary>
/// 编号
/// </summary>
public virtual int Id

{
get

{
return _id;
}
set

{
_id = value;
}
}


/**//// <summary>
/// 名称
/// </summary>
public virtual string Name

{
get

{
return _name;
}
set

{
_name = value;
}
}


/**//// <summary>
/// 密码
/// </summary>
public virtual string Pwd

{
get

{
return _pwd;
}
set

{
_pwd = value;
}
}
}
}

6).编写User类的映射配置文件:User.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NhibernateSample1.User,NhibernateSample1" table="Users" lazy="false">
<id name="Id" column="Id" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property>
<property name="Pwd" column="Pwd" type="string" length="64" not-null="true"></property>
</class>
</hibernate-mapping>
注意:该映射文件的属性中的生成操作必须为:嵌入的资源.
7).编写管理ISession对象的辅助类: NHibernateHelper.cs,代码为: