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,添加代码:
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,代码为:
注:因为我用的是单元测试,所以这里的配置文件路径写成固定的了。如果换成windows或者web程序,可以直接去掉该路径。
8) 编写测试crud类:userfixue
扫描关注微信公众号