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


    内容摘要

        准备工作

        开发流程

        程序开发

      一、准备工作

        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

      

     1 /// <summary>
     2  2     /// 商品
     3  3     /// </summary>
     4  4     public class Product
     5  5     {
     6  6         /// <summary>
     7  7         /// ID
     8  8         /// </summary>
     9  9         public virtual Guid ID { get; set; }
    10 10 
    11 11         /// <summary>
    12 12         /// 编号
    13 13         /// </summary>
    14 14         public virtual string Code { get; set; }
    15 15 
    16 16         /// <summary>
    17 17         /// 名称
    18 18         /// </summary>
    19 19         public virtual string Name { get; set; }
    20 20 
    21 21         /// <summary>
    22 22         /// 规格
    23 23         /// </summary>
    24 24         public virtual string QuantityPerUnit { get; set; }
    25 25 
    26 26         /// <summary>
    27 27         /// 单位
    28 28         /// </summary>
    29 29         public virtual string Unit { get; set; }
    30 30 
    31 31         /// <summary>
    32 32         /// 售价
    33 33         /// </summary>
    34 34         public virtual decimal SellPrice { get; set; }
    35 35 
    36 36         /// <summary>
    37 37         /// 进价
    38 38         /// </summary>
    39 39         public virtual decimal BuyPrice { get; set; }
    40 40 
    41 41         /// <summary>
    42 42         /// 备注
    43 43         /// </summary>
    44 44         public virtual string Remark { get; set; }
    45 45     }
    Product.cs

            

        编写映射文件Product.hbm.xml

      

     1 <?xml version="1.0" encoding="utf-8" ?>
     2 
     3 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
     4   <class name="Product" table="T_Product" lazy="true" >
     5     <id name="ID" column="ID" type="Guid" >
     6       <generator class="assigned" />
     7     </id>
     8 
     9     <property name="Code" type="string">
    10       <column name="Code" length="50"/>
    11     </property>
    12 
    13     <property name="Name" type="string">
    14       <column name="Name" length="50"/>
    15     </property>
    16     
    17     <property name="QuantityPerUnit" type="string">
    18       <column name="QuantityPerUnit" length="50"/>
    19     </property>
    20 
    21     <property name="Unit" type="string">
    22       <column name="Unit" length="50"/>
    23     </property>
    24 
    25 
    26     <property name="SellPrice" type="decimal">
    27       <column name="SellPrice" precision="14" scale="2"/>
    28     </property>
    29 
    30     <property name="BuyPrice" type="decimal">
    31       <column name="BuyPrice" precision="14" scale="2"/>
    32     </property>
    33 
    34     <property name="Remark" type="string">
    35       <column name="Remark" length="200"/>
    36     </property>
    37 
    38   </class>
    39 </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

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

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

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

     1 [TestFixture]
     2     public class NHibernateInit
     3     {
     4         [Test]
     5         public void InitTest()
     6         {
     7             var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
     8             using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) { }
     9         }
    10     }
    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

      

     1 public interface IProductDao
     2     {
     3         object Save(Product entity);
     4 
     5         void Update(Product entity);
     6 
     7         void Delete(Product entity);
     8 
     9         Product Get(object id);
    10 
    11         Product Load(object id);
    12 
    13         IList<Product> LoadAll();
    14     }
    15 
    16 
    17  public class ProductDao : IProductDao
    18     {
    19         private ISessionFactory sessionFactory;
    20 
    21         public ProductDao()
    22         {
    23             var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
    24             sessionFactory = cfg.BuildSessionFactory();
    25         }
    26 
    27         public object Save(Domain.Product entity)
    28         {
    29             using (ISession session = sessionFactory.OpenSession())
    30             {
    31                 var id = session.Save(entity);
    32                 session.Flush();
    33                 return id;
    34             }
    35         }
    36 
    37         public void Update(Domain.Product entity)
    38         {
    39             using (ISession session = sessionFactory.OpenSession())
    40             {
    41                 session.Update(entity);
    42                 session.Flush();
    43             }
    44         }
    45 
    46         public void Delete(Domain.Product entity)
    47         {
    48             using (ISession session = sessionFactory.OpenSession())
    49             {
    50                 session.Delete(entity);
    51                 session.Flush();
    52             }
    53         }
    54 
    55         public Domain.Product Get(object id)
    56         {
    57             using (ISession session = sessionFactory.OpenSession())
    58             {
    59                 return session.Get<Domain.Product>(id);
    60             }
    61         }
    62 
    63         public Domain.Product Load(object id)
    64         {
    65             using (ISession session = sessionFactory.OpenSession())
    66             {
    67                 return session.Load<Domain.Product>(id);
    68             }
    69         }
    70 
    71         public IList<Domain.Product> LoadAll()
    72         {
    73             using (ISession session = sessionFactory.OpenSession())
    74             {
    75                 return session.Query<Domain.Product>().ToList();
    76             }
    77         }
    78 }
    ProductDao

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

     1 [TestFixture]
     2     public class ProductDaoTest
     3     {
     4         private IProductDao productDao;
     5 
     6         [SetUp]
     7         public void Init()
     8         {
     9             productDao = new ProductDao();
    10         }
    11 
    12         [Test]
    13         public void SaveTest()
    14         {
    15             var product = new Domain.Product
    16             {
    17                 ID = Guid.NewGuid(),
    18                 BuyPrice = 10M,
    19                 Code = "ABC123",
    20                 Name = "电脑",
    21                 QuantityPerUnit = "20x1",
    22                 SellPrice = 11M,
    23                 Unit = ""
    24             };
    25 
    26             var obj = this.productDao.Save(product);
    27 
    28             Assert.NotNull(obj);
    29         }
    30 
    31         [Test]
    32         public void UpdateTest()
    33         {
    34             var product = this.productDao.LoadAll().FirstOrDefault();
    35             Assert.NotNull(product);
    36 
    37             product.SellPrice = 12M;
    38 
    39             Assert.AreEqual(12M, product.SellPrice);
    40         }
    41 
    42         [Test]
    43         public void DeleteTest()
    44         {
    45             var product = this.productDao.LoadAll().FirstOrDefault();
    46             Assert.NotNull(product);
    47 
    48             var id = product.ID;
    49             this.productDao.Delete(product);
    50             Assert.Null(this.productDao.Get(id));
    51         }
    52 
    53         [Test]
    54         public void GetTest()
    55         {
    56             var product = this.productDao.LoadAll().FirstOrDefault();
    57             Assert.NotNull(product);
    58 
    59             var id = product.ID;
    60             Assert.NotNull(this.productDao.Get(id));
    61         }
    62 
    63         [Test]
    64         public void LoadTest()
    65         {
    66             var product = this.productDao.LoadAll().FirstOrDefault();
    67             Assert.NotNull(product);
    68 
    69             var id = product.ID;
    70             Assert.NotNull(this.productDao.Get(id));
    71         }
    72 
    73         [Test]
    74         public void LoadAllTest()
    75         {
    76             var count = this.productDao.LoadAll().Count;
    77             Assert.True(count > 0);
    78         }
    79 }
    ProductDaoTest

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

      图3.3.2

      

      

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

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

  • 相关阅读:
    ERROR: Couldn't connect to Docker daemon at http+docker://localunixsocket
    plainless script for es
    canal 代码阅读
    elasticsearch 之编译过程
    nfs 共享目录
    canal mysql slave
    yum 运行失败
    linux 几种服务类型
    2019-04-16 SpringMVC 学习笔记
    2019-04-10 集成JasperReport
  • 原文地址:https://www.cnblogs.com/jett010/p/4826226.html
Copyright © 2020-2023  润新知