内容摘要

    准备工作

    开发流程

    程序开发

  一、准备工作

    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

  

 /// <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.cs

        

    编写映射文件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=""/>
</property> <property name="Name" type="string">
<column name="Name" length=""/>
</property> <property name="QuantityPerUnit" type="string">
<column name="QuantityPerUnit" length=""/>
</property> <property name="Unit" type="string">
<column name="Unit" length=""/>
</property> <property name="SellPrice" type="decimal">
<column name="SellPrice" precision="" scale=""/>
</property> <property name="BuyPrice" type="decimal">
<column name="BuyPrice" precision="" scale=""/>
</property> <property name="Remark" type="string">
<column name="Remark" length=""/>
</property> </class>
</hibernate-mapping>

Product.hbm.xml

  然后,将映射文件“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

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

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

hibernate.cfg.xml

  创建“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()) { }
}
}

NHibernateInit.cs

  复制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类

  

 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();
}
}
}

ProductDao

  然后在测试项目“NHibernateTest”中编写测试类“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 > );
}
}

ProductDaoTest

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

  图3.3.2

  

  

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

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

NHibernate从入门到精通系列(3)——第一个NHibernate应用程序的更多相关文章

  1. NHibernate从入门到精通系列

    http://www.cnblogs.com/GoodHelper/archive/2011/02/17/1948744.html NHibernate从入门到精通系列(4)——持久对象的生命周期(上 ...

  2. [大数据从入门到放弃系列教程]第一个spark分析程序

    [大数据从入门到放弃系列教程]第一个spark分析程序 原文链接:http://www.cnblogs.com/blog5277/p/8580007.html 原文作者:博客园--曲高终和寡 **** ...

  3. NHibernate从入门到精通系列(1)——NHibernate概括

    内容摘要 NHibernate简介 ORM简介 NHibernate优缺点 一.NHibernate简介 什么是?NHibernate?NHibernate是一个面向.NET环境的对象/关系数据库映射 ...

  4. NHibernate从入门到精通系列(2)——NHibernate环境与结构体系

    内容摘要 NHibernate的开发环境 NHibernate的结构体系 NHibernate的配置 一.NHibernate的开发环境 NHibernate的英文官方网站为:http://nhfor ...

  5. NHibernate从入门到精通系列——NHibernate环境与结构体系

    内容摘要 NHibernate的开发环境 NHibernate的结构体系 NHibernate的配置 一.NHibernate的开发环境 NHibernate的英文官方网站为:http://nhfor ...

  6. Provisioning Services 7.6 入门到精通系列之一:PVS前期规划

    1.  Provisioning Services 产品概述 Provisioning Services (简称PVS)采用了一种与传统映像解决方案截然不同的方法,从根本上改变了硬件与依托硬件而运行的 ...

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

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

  8. 办公软件Office PPT 2010视频教程从入门到精通系列教程(22课时)

    办公软件Office PPT 2010视频教程从入门到精通系列教程(22课时) 乔布斯的成功离不开美轮美奂的幻灯片效果,一个成功的商务人士.部门经理也少不了各种各样的PPT幻灯片.绿色资源网给你提供了 ...

  9. Selenium 入门到精通系列:六

    Selenium 入门到精通系列 PS:Checkbox方法 例子 HTML: <html> <head> <title>测试页面</title> &l ...

随机推荐

  1. 读取超大Excel(39万行数据)

    有个学长需要处理Excel数据,Excel数据共有39W,将数据读取后处理并导出数据.最开始尝试了 NPOI ,发现NPOI 并不能完成该项任务,随后尝试引用的com组件:Microsoft.Offi ...

  2. Cucumber 相关资源

    Cucumber support: https://cucumber.io/support yan1234abcd的专栏:http://blog.csdn.net/yan1234abcd/articl ...

  3. xampp配置多端口访问

    1.修改D:\xampp\apache\conf\extra中的httpd-vhosts.conf文件,在最底部添加 <VirtualHost *:8080> ##需要监听的端口号 Ser ...

  4. Java中的懒汉式单例与饿汉式单例实例详解

    懒汉式单例:线程非安全,当被调用的时候才创建实例,效率较高 public class LazySingleton { private static LazySingleton lazySingleto ...

  5. Redis 中的数据类型及基本操作

    Redis 内置的数据类型有 5种:字符串String.哈希Hash.列表List.集合Set.有序集合ZSet 字符串类型 String 是 Redis 中最基本的类型,一个 key 对应着一个 v ...

  6. 【Bootstrap】优秀小插件收集

    Bootstrap中不乏很多优秀的小插件来让界面更加漂亮.比如之前做过笔记的bootstrap-fileinput,select2,datetimepicker等都是属于这一系列的.这些相对而言比较大 ...

  7. linux下安装Sublime Text3并将它的快捷方式放进启动器中

    Sublime Text是一个代码编辑器,我主要是用它来编辑python.下面就来简单说明下它在linux的安装过程吧! 1.添加sublime text3的仓库 首先按下快捷键ctrl+alt+t打 ...

  8. ElasticSearch之 控制相关度原理讲解

    控制相关度 相关度评分背后的理论 如何计算评分的 Lucene 使用布尔模型(Boolean model) 查找匹配文档 并主要的借鉴了 词频/逆向文档频率(term frequency/invers ...

  9. Android 源代码结构

    简介 在使用Andriod SDK进行应用程序开发的时候,我们需要对源代码进行调试,有可能需要进入到某个Android API函数内部进行跟踪调试.但是,如果目标版本的SDK没有关联对应版本的源代码的 ...

  10. SSH三大框架的整合

    SSH三个框架的知识点 一.Hibernate框架 1. Hibernate的核心配置文件 1.1 数据库信息.连接池配置 1.2 Hibernate信息 1.3 映射配置 1.4 Hibernate ...