内容摘要

    准备工作

    开发流程

    程序开发

  一、准备工作

    1.1开发环境

      开发工具:VS2008以上,我使用的是VS2010

      数据库:任意关系型数据库,我使用的是SQL Server 2005 Express

    1.2测试环境

      nunit 2.5.7

  二、开发流程

  NHibernate程序的开发流程是:

    (1).编写领域类与映射文件

    (2).使用NHibernate工具生成对应的数据库结构

    (3).编写DAO(数据库访问对象)

    (4).使用NUnit测试DAO(数据访问对象)的增、删、该、查方法

  三、程序开发

  3.1 建立Domain项目,如图3.1.1所示。

  

图3.1.1

    编写类文件Product.cs

Product

 /// <summary>
    /// 商品
    /// </summary>
    public class Product
    {
        /// <summary>
        /// ID
        /// </summary>
        public virtual Guid ID { get; set; }

/// <summary>
        /// 编号
        /// </summary>
        public virtual string Code { get; set; }

/// <summary>
        /// 名称
        /// </summary>
        public virtual string Name { get; set; }

/// <summary>
        /// 规格
        /// </summary>
        public virtual string QuantityPerUnit { get; set; }

/// <summary>
        /// 单位
        /// </summary>
        public virtual string Unit { get; set; }

/// <summary>
        /// 售价
        /// </summary>
        public virtual decimal SellPrice { get; set; }

/// <summary>
        /// 进价
        /// </summary>
        public virtual decimal BuyPrice { get; set; }

/// <summary>
        /// 备注
        /// </summary>
        public virtual string Remark { get; set; }
    }

    编写映射文件Product.hbm.xml

Product.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
  <class name="Product" table="T_Product" lazy="true" >
    <id name="ID" column="ID" type="Guid" >
      <generator class="assigned" />
    </id>

<property name="Code" type="string">
      <column name="Code" length="50"/>
    </property>

<property name="Name" type="string">
      <column name="Name" length="50"/>
    </property>
    
    <property name="QuantityPerUnit" type="string">
      <column name="QuantityPerUnit" length="50"/>
    </property>

<property name="Unit" type="string">
      <column name="Unit" length="50"/>
    </property>

<property name="SellPrice" type="decimal">
      <column name="SellPrice" precision="14" scale="2"/>
    </property>

<property name="BuyPrice" type="decimal">
      <column name="BuyPrice" precision="14" scale="2"/>
    </property>

<property name="Remark" type="string">
      <column name="Remark" length="200"/>
    </property>

</class>
</hibernate-mapping>

  然后,将映射文件“Product.hbm.xml”的属性“生成方式”设置为“嵌入的资源”,如图3.1.2所示。

图3.1.2

  3.2 建立名为“NHibernateTest”的项目,如图3.2.1所示

图3.2.1

  引用程序集“Antlr3.Runtime.dll”,“Iesi.Collections.dll”,“NHibernate.dll”,“Remotion.Data.Linq.dll”,“nunit.framework.dll”,如图3.2.2所示

图3.2.2

  然后音乐Domain项目,复制并粘贴NHibernate的配置模板到项目中,如图3.2.3所示

  图3.2.3

  修改该文件的属性为“始终复制

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- 
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it 
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="NHibernateTest">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string">
      server=.\SQLEXPRESS;database=NHibernateDemo;uid=sa;pwd=;
    </property>
        <property name="adonet.batch_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
        <property name="use_outer_join">true</property>
        <property name="command_timeout">60</property>
    <property name="hbm2ddl.auto">update</property>
        <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
        <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    <mapping assembly="Domain"/>
    </session-factory>
</hibernate-configuration>

  创建“NHibernateInit.cs”类文件,用于初始化数据库的表结构

NHibernateInit.cs

[TestFixture]
    public class NHibernateInit
    {
        [Test]
        public void InitTest()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) { }
        }
    }

  复制proxyfactory类的程序集“LinFu.DynamicProxy.dll”和“NHibernate.ByteCode.LinFu.dll”到项目中,并修改生成方式,如图3.2.4所示

图3.2.4

  设置项目属性的启动操作,为“启动外部程序”,然后选择NUnit应用程序的路径。如图3.2.5所示。

图3.2.5

  打开SQL Server Management Studio Express,创建名为“NHibernateDemo”的数据库,如图3.2.6

图3.2.6

  启用NUnit,选择名称“NHibernateTest.dll”的程序集。如图3.2.7所示。接着,点击“run”按钮运行NUnit。

图3.2.7

  这时,我们再打开数据库,就会发现,NHibernate已经为我们建立了“T_Product”表,如图3.2.8所示。

图3.2.8

  3.3 编写DAO(数据库访问对象),建立名为“Dao”的项目。如图3.3.1所示。

图3.3.1

  引用项目所需的程序集,接着编写IProductDao接口和 ProductDao类

ProductDao

 public interface IProductDao
    {
        object Save(Product entity);

void Update(Product entity);

void Delete(Product entity);

Product Get(object id);

Product Load(object id);

IList<Product> LoadAll();
    }

public class ProductDao : IProductDao
    {
        private ISessionFactory sessionFactory;

public ProductDao()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
            sessionFactory = cfg.BuildSessionFactory();
        }

public object Save(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                var id = session.Save(entity);
                session.Flush();
                return id;
            }
        }

public void Update(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                session.Update(entity);
                session.Flush();
            }
        }

public void Delete(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                session.Delete(entity);
                session.Flush();
            }
        }

public Domain.Product Get(object id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Get<Domain.Product>(id);
            }
        }

public Domain.Product Load(object id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Load<Domain.Product>(id);
            }
        }

public IList<Domain.Product> LoadAll()
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Query<Domain.Product>().ToList();
            }
        }
}

  然后在测试项目“NHibernateTest”中编写测试类“ProductDaoTest”。

ProductDaoTest

[TestFixture]
    public class ProductDaoTest
    {
        private IProductDao productDao;

[SetUp]
        public void Init()
        {
            productDao = new ProductDao();
        }

[Test]
        public void SaveTest()
        {
            var product = new Domain.Product
            {
                ID = Guid.NewGuid(),
                BuyPrice = 10M,
                Code = "ABC123",
                Name = "电脑",
                QuantityPerUnit = "20x1",
                SellPrice = 11M,
                Unit = "台"
            };

var obj = this.productDao.Save(product);

Assert.NotNull(obj);
        }

[Test]
        public void UpdateTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

product.SellPrice = 12M;

Assert.AreEqual(12M, product.SellPrice);
        }

[Test]
        public void DeleteTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

var id = product.ID;
            this.productDao.Delete(product);
            Assert.Null(this.productDao.Get(id));
        }

[Test]
        public void GetTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

var id = product.ID;
            Assert.NotNull(this.productDao.Get(id));
        }

[Test]
        public void LoadTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

var id = product.ID;
            Assert.NotNull(this.productDao.Get(id));
        }

[Test]
        public void LoadAllTest()
        {
            var count = this.productDao.LoadAll().Count;
            Assert.True(count > 0);
        }
}

  最后运行NUnit测试该项目。效果如图3.3.2所示。

  图3.3.2

  好了,一个NHibernate完整的项目就做完了。从中我们可以发现,此应用程序项目没有编写一条SQL语句,就能实现数据的增、删、该、查。

  这样一来,便简化了我们的项目开发。O(∩_∩)O~

  代码下载

  出处:http://www.cnblogs.com/GoodHelper/archive/2011/02/16/nhibernate_03.html

转载于:https://www.cnblogs.com/chlyzone/archive/2011/03/04/1970530.html

NHibernate从入门到精通系列(3)——第一个NHibernate应用程序相关推荐

  1. NHibernate从入门到精通系列(7)——多对一关联映射

    内容摘要 多对一关联映射概括 多对一关联映射插入和查询 多对一关联映配置介绍 一.多对一关联映射概括 关联关系是实体类与实体类之间的结构关系,分别为"多对一"."一对一& ...

  2. NHibernate从入门到精通系列(5)——持久对象的生命周期(下)

    内容摘要 持久化类 持久化生命周期中的回调 合法性验证回调 一.持久化类(Persistent Classes) 1.1 什么是持久化类 回答这个问题之前先回答什么是持久化.所谓的持久化就是把数据(如 ...

  3. 【ArcGIS遇上Python】从入门到精通系列之第一章:ArcGIS Python简介

    文章目录 1. Python简介 2. Python的特点 3. ArcGIS的脚本语言 4. ArcGIS中的Python脚本编辑器 1. Python简介 Python是一种跨平台的计算机程序设计 ...

  4. Linux从入门到精通系列之PPTP

    Linux从入门到精通系列之PPTP 今天我们来说下怎么在linux环境下如何搭建PPTP-×××,PPTP(Point to Point Tunneling Protocol),即点对点隧道协议.该 ...

  5. Jenkins pipeline 入门到精通系列文章

    Jenkins2 入门到精通系列文章. Jenkins2 下载与启动 jenkins2 插件安装 jenkins2 hellopipeline jenkins2 pipeline介绍 jenkins2 ...

  6. html5从基础到入门,Html5从入门到精通系列2:Html5基础

    Html5从入门到精通系列2:Html5基础 (2015-04-04 11:36:53) 标签: html5 html5教程 html5视频教程 html5从入门到精通 2-1.1.HTML5简介.M ...

  7. ArcGIS10从入门到精通系列实验图文教程(附配套实验数据持续更新)

    文章目录 1. 专栏简介 2. 专栏地址 3. 专栏目录 1. 专栏简介 本教程<ArcGIS从入门到精通系列实验教程>内容包括:ArcGIS平台简介.ArcGIS应用基础.空间数据的采集 ...

  8. OpenShift从入门到精通系列之一:通过OpenShift实现数字化转型

    OpenShift从入门到精通系列之一:通过OpenShift实现数字化转型 一.企业数字化转型之PaaS 二.企业数字化转型之DevOps 三.企业数字化转型之微服务 四.微服务架构的主要类型 五. ...

  9. Vue3+TypeScript从入门到精通系列之:Try changing the lib compiler option to es2015 or later

    Vue3+TypeScript从入门到精通系列之:Try changing the lib compiler option to es2015 or later tsc ./泛型接口.ts tsc编译 ...

最新文章

  1. 字符输出流的基本使用_写出单个字符到文件
  2. 在现有的python环境下创建另一个python版本【亲测有效】
  3. jsp快到截止日期字体颜色变色_jsp页面中字体变色问题 - Java / Web 开发
  4. FreeRTOS--堆内存管理(二)
  5. jmeter java性能_jmeter java性能测试
  6. fd抓包数据类型_fd抓包教程 FD入门简介(配置教程) fd视频教程2016
  7. EditPlus 快捷键大全
  8. Redis 入门指南
  9. ov5640帧率配置_OV5640摄像头开窗大小,输出窗口大小,帧率等设置
  10. 2018 Google IO大会来了
  11. 华为服务器怎么设置u盘启动安装系统,服务器怎么设置u盘启动
  12. 苹果截屏快捷键_MacOS截屏的那些事儿
  13. 关于php上传多张图片时,选择图片后就可以预览的问题
  14. Spring源码分析(二)BeanFactoryPostProcessor之ConfigurationClassPostProcessor的调用过程
  15. Cloud Computing HCIP④-Fusion Access 桌面云
  16. html编辑器增加超级链接,ueditor1.2.1修改超链接默认值,ueditor编辑器新窗口打开连接...
  17. 思维导图-第二章 会计政策和会计估计及其变更
  18. 数字信号处理——FFT运算模块设计(3)
  19. 人工智能与机器学习----SVM算法深入探究
  20. 图机器学习【从理论到实战】

热门文章

  1. 学生宿舍管理项目开发计划书_第六组学生宿舍管理系统项目计划书
  2. mysql tiqu mssql_mysql数据表如何导入MSSQL中
  3. java中的事件派发机制_事件派发器模式
  4. 定义斜体文本的html标签,HTML 文本格式化
  5. [20180604]在内存修改数据(bbed).txt
  6. windows和linux文件输 - ftp
  7. iOS定位服务CoreLocation
  8. Sixpack —— 支持多语言的 A/B 测试框架
  9. 无边框对话框拖动改变大小的实现总结
  10. iPhone/iPad/iPod touch编程时版本区分