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

来源:互联网 发布:c 程序员职业寿命 编辑:程序博客网 时间:2024/05/17 04:31

内容摘要

    准备工作

    开发流程

    程序开发

 

  一、准备工作

    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~


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 淘宝的淘金币快过期了怎么办 乐透啦彩票让骗了6万怎么办 交了认筹金不能进抢购平台怎么办 爱奇艺会文学会员办了想退款怎么办 海淘信用卡入账但是砍单怎么办 褐色分泌物流了好几天了怎么办? 淘宝买的衣服一直不发货怎么办 从国外寄东西到国内被税了怎么办 百度网盘上传文件数量有限制怎么办 腾讯视频上传文件过限制大小怎么办 三星s7打网页又卡又慢怎么办 路由器的上网账号和口令忘了怎么办 小米笔记本移动热点连接不上怎么办 移动宽带密码重置后认证失败怎么办 移动光纤不记得账号和密码怎么办? 宽带为什么交了钱还是不能用怎么办 小孩被虎牙直播诱导支付了款怎么办 房间里4g网络信号差怎么办 移动4g网络信号不满格怎么办 大风号无法上传视频暂停服务怎么办 过了竞牌保证金交付时间怎么办 亚马逊产品上架后货物没到怎么办 工行企业网银证书过期了怎么办 海淘转运地址国家填错了怎么办 集装箱实重与申报重量不一样怎么办 微博复制的淘口令找不到了怎么办 买了移动手机不能用联通卡怎么办 移动手机用联通卡网速慢怎么办 移动手机插联通卡没反应怎么办 移动手机办了联通大王卡怎么办 qq被冻结但是有至尊宝怎么办 qq被冻结了有至尊宝怎么办 移动电话卡注销了里面的钱怎么办 罗麦的oa上经理喜报没截图怎么办 工行融e联登录密码忘了怎么办 融e借有额度秒拒怎么办 工行银行柜台办理融e借怎么办 地球末日生存破解版金币没了怎么办 手机被别人骗走了里面的微信怎么办 在微信里面被做微商的骗了钱怎么办 在qq上骗了人50怎么办