zoukankan      html  css  js  c++  java
  • 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

      

    复制代码
     /// <summary>
        
    /// 商品
        
    /// </summary>
        public class Product
        {
            
    /// <summary>
            
    /// ID
            
    /// </summary>
            public virtual Guid ID { getset; }

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

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

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

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

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

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

            
    /// <summary>
            
    /// 备注
            
    /// </summary>
            public virtual string Remark { getset; }
        }
    复制代码

            

        编写映射文件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

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

    复制代码
    <?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”类文件,用于初始化数据库的表结构

    复制代码
    [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

      

    复制代码
     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”。

    复制代码
    [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

      欢迎转载,但需保留版权。

  • 相关阅读:
    Android 5.0以上手机出现找不到so文件
    面向对象:析构方法-__del__
    面向对象:类中的反射及其应用
    面向对象:内置方法call、len、new、str
    面向对象-内置函数isinstance()和issubclass()
    面向对象:类方法(classmethod),静态方法(staticmethod)
    面向对象:属性-装饰器函数@property
    面向对象的三大特性: 封装
    面向对象:接口类、抽象类
    面向对象的三大特性: 多态
  • 原文地址:https://www.cnblogs.com/xwj517537691/p/3117439.html
Copyright © 2011-2022 走看看