Nhibernate学习之起步篇-1

1. 学习目的
学习Nhibernate基础知识。掌握Nhibernate的配置方法,实现对单表的简单操作,如:创建表,查询,添加,删除,修改。
2. 开发环境+前期准备
开发环境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition
前期准备: Nhibernate框架,我用的目前最新版NHibernate-1.2.0.CR1, 下载地址:        http://downloads.sourceforge.net/nhibernate/NHibernate-1.2.0.CR1.msi?modtime=1172161735&big_mirror=0
3. 开发步骤:
1).双击下载下来的NHibernate-1.2.0.CR1.msi,将其安装到某个目录,我的目录为: E:\download project\orm\nhibernate.,打开该目录,即可以看到bin,doc,src三个子目录,分别为Realse好的dll或者exe目录,文档说明目录,和源程序目录.
2).打开visual studio 2005,创建类库项目NhibernateSample1
3).在解决方案管理其中,右键点击引用-添加引用,在选项卡种选择浏览,设定查找范围为:E:\download project\orm\nhibernate\bin,添加对Nhibernate.dll,log4net.dll, Iesi.Collections, HashCodeProvider四个dll的引用.
4).打开SQL Server Management Studio,创建数据库nhibernate。
5).在解决方案管理器中添加hibernate.cfg.xml文件。将下面代码粘贴到此文件: 

None.gif <? xml version="1.0" encoding="utf-8"  ?>
None.gif < hibernate-configuration   xmlns ="urn:nhibernate-configuration-2.2"  >
None.gif     < session-factory  name ="NHibernate.Test" >
None.gif         <!--  properties  -->
None.gif         < property  name ="connection.provider" > NHibernate.Connection.DriverConnectionProvider </ property >
None.gif         < property  name ="connection.driver_class" > NHibernate.Driver.SqlClientDriver </ property >
None.gif         < property  name ="connection.connection_string" > Server=127.0.0.1;initial catalog=nhibernate;uid=sa;pwd=123; </ property >
None.gif         < property  name ="show_sql" > false </ property >
None.gif         < property  name ="dialect" > NHibernate.Dialect.MsSql2005Dialect </ property >
None.gif         < property  name ="use_outer_join" > true </ property >
None.gif         <!--  mapping files  -->
None.gif         < mapping  assembly ="NhibernateSample1"  />
None.gif     </ session-factory >     
None.gif </ hibernate-configuration >
None.gif

 该文件是Nhibernate的配置文件,其中connection.connection_string为数据库连接字符串,Dialect项因为我用的是SQL2005,所以为:MsSql2005Dialect注意:<mapping assembly=”NhibernateSample1”/>表示映射NhibernateSample1程序集下的所有类,所以以后不要需要Configuration.AddClass(..)了;

6).添加类文件:User.cs,添加代码: 

None.gif using  System;
None.gif using  System.Collections.Generic;
None.gif using  System.Text;
None.gif
None.gif namespace  NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif dot.gif {
InBlock.gif    public class User
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        private int _id;
InBlock.gif        private string _name;
InBlock.gif        private string _pwd;
ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 编号
ExpandedSubBlockEnd.gif        /// </summary>

InBlock.gif        public virtual int Id
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            get
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                return _id;
ExpandedSubBlockEnd.gif            }

InBlock.gif            set
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                _id = value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 名称
ExpandedSubBlockEnd.gif        /// </summary>

InBlock.gif        public virtual string Name
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            get
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                return _name;
ExpandedSubBlockEnd.gif            }

InBlock.gif            set
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                _name = value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 密码
ExpandedSubBlockEnd.gif        /// </summary>

InBlock.gif        public virtual string Pwd
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            get
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                return _pwd;
ExpandedSubBlockEnd.gif            }

InBlock.gif            set
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                _pwd = value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

 6).编写User类的映射配置文件:User.hbm.xml

None.gif <? xml version="1.0" encoding="utf-8"  ?>
None.gif < hibernate-mapping  xmlns ="urn:nhibernate-mapping-2.2" >
None.gif   < class  name ="NhibernateSample1.User,NhibernateSample1"  table ="Users"  lazy ="false" >
None.gif     < id  name ="Id"  column ="Id"  unsaved-value ="0" >
None.gif       < generator  class ="native"  />
None.gif     </ id >
None.gif     < property  name ="Name"  column ="Name"  type ="string"  length ="64"  not-null ="true"  unique ="true" ></ property >
None.gif     < property  name ="Pwd"   column ="Pwd"   type ="string"  length ="64"  not-null ="true" ></ property >
None.gif   </ class >
None.gif </ hibernate-mapping >

  注意:该映射文件的属性中的生成操作必须为:嵌入的资源.

7).编写管理ISession对象的辅助类: NHibernateHelper.cs,代码为:

None.gif
None.gif using  System;
None.gif using  System.Web;
None.gif using  NHibernate;
None.gif using  NHibernate.Cfg;
None.gif
None.gif namespace  NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif dot.gif {
InBlock.gif    public sealed class NHibernateHelper
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        private static readonly ISessionFactory sessionFactory;
InBlock.gif
InBlock.gif        static NHibernateHelper()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            sessionFactory = new Configuration().Configure(@"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml").BuildSessionFactory();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        public static ISession GetCurrentSession()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{             
InBlock.gif            ISession currentSession = sessionFactory.OpenSession();
InBlock.gif            return currentSession;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        public static void CloseSessionFactory()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            if (sessionFactory != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                sessionFactory.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
注:因为我用的是单元测试,所以这里的配置文件路径写成固定的了。如果换成windows或者Web 程序,可以直接去掉该路径。

8) 编写测试CRUD:UserFixue

None.gif using  System;
None.gif using  System.Collections.Generic;
None.gif using  System.Text;
None.gif using  NHibernate;
None.gif using  NHibernate.Cfg;
None.gif using  NHibernate.Tool.hbm2ddl;
None.gif namespace  NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif dot.gif {
InBlock.gif    public class UserFixure
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        private ISession session;
InBlock.gif        public UserFixure()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 创建表
ExpandedSubBlockEnd.gif        /// </summary>

InBlock.gif        public bool ExportTable()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                Configuration cfg = new Configuration().Configure(@"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml");
InBlock.gif                session = NHibernateHelper.GetCurrentSession();
InBlock.gif                ITransaction transaction = session.BeginTransaction();
InBlock.gif                new SchemaExport(cfg).Create(true, true);
InBlock.gif                transaction.Commit();
InBlock.gif                return true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                throw ex; 
ExpandedSubBlockEnd.gif            }

InBlock.gif            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 添加
ExpandedSubBlockEnd.gif        /// </summary>

InBlock.gif        public int Add()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                User u = new User();
InBlock.gif                u.Name = Guid.NewGuid().ToString();
InBlock.gif                u.Pwd = "124";
InBlock.gif                session = NHibernateHelper.GetCurrentSession();
InBlock.gif                ITransaction transaction = session.BeginTransaction();
InBlock.gif                session.Save(u);
InBlock.gif                transaction.Commit();
InBlock.gif                return u.Id;
ExpandedSubBlockEnd.gif            }

InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                throw ex;
ExpandedSubBlockEnd.gif            }

InBlock.gif            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 更新
InBlock.gif        /// </summary>
ExpandedSubBlockEnd.gif        /// <param name="uid"></param>

InBlock.gif        public bool Update(int uid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session = NHibernateHelper.GetCurrentSession();
InBlock.gif                ITransaction transaction = session.BeginTransaction();
InBlock.gif                User u = session.Load(typeof(User), uid) as User;
InBlock.gif                if (u != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
InBlock.gif                    u.Name = "updatedName";
InBlock.gif                    session.SaveOrUpdate(u);
InBlock.gif                    transaction.Commit();
InBlock.gif                    u = session.Load(typeof(User), uid) as User;
InBlock.gif                    if (u.Name == "updatedName")
ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
InBlock.gif                        return true;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                throw ex;
ExpandedSubBlockEnd.gif            }

InBlock.gif            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
InBlock.gif        /// 删除
InBlock.gif        /// </summary>
InBlock.gif        /// <param name="uid"></param>
ExpandedSubBlockEnd.gif        /// <returns></returns>

InBlock.gif        public bool Delete(int uid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session = NHibernateHelper.GetCurrentSession();
InBlock.gif                ITransaction transaction = session.BeginTransaction();
InBlock.gif                User u = session.Get(typeof(User), uid) as User;
InBlock.gif                if (u != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
InBlock.gif                   session.Delete(u);
InBlock.gif                   transaction.Commit();
InBlock.gif                   u = session.Get(typeof(User), uid) as User;
InBlock.gif                   if (u == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
InBlock.gif                       return true;
ExpandedSubBlockEnd.gif                   }

ExpandedSubBlockEnd.gif                }

InBlock.gif                return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                throw ex;
ExpandedSubBlockEnd.gif            }

InBlock.gif            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        public System.Collections.IList Query()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session = NHibernateHelper.GetCurrentSession();
InBlock.gif                ITransaction transaction = session.BeginTransaction();
InBlock.gif                System.Collections.IList list= session.CreateQuery("select u from User as u").List();
InBlock.gif                transaction.Commit();
InBlock.gif                return list;
ExpandedSubBlockEnd.gif            }

InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                throw ex;
ExpandedSubBlockEnd.gif            }

InBlock.gif            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

9) 创建新单元测试项目 : TestProject1, 添加 NhibernateSample1 的引用
10 )创建单元测试类 : UnitTest1.cs, 并输入如下代码 :
None.gif using  System;
None.gif using  System.Text;
None.gif using  System.Collections.Generic;
None.gif using  Microsoft.VisualStudio.TestTools.UnitTesting;
None.gif using  NhibernateSample1;
None.gif
None.gif namespace  TestProject1
ExpandedBlockStart.gifContractedBlock.gif dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
InBlock.gif    /// UnitTest1 的摘要说明
ExpandedSubBlockEnd.gif    /// </summary>

InBlock.gif    [TestClass]
InBlock.gif    public class UnitTest1
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        public UnitTest1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            //
InBlock.gif            // TODO: 在此处添加构造函数逻辑
InBlock.gif            //
ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        其他测试属性#region 其他测试属性
InBlock.gif        //
InBlock.gif        // 您可以在编写测试时使用下列其他属性:
InBlock.gif        //
InBlock.gif        // 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
InBlock.gif        // [ClassInitialize()]
InBlock.gif        // public static void MyClassInitialize(TestContext testContext) { }
InBlock.gif        //
InBlock.gif        // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
InBlock.gif        // [ClassCleanup()]
InBlock.gif        // public static void MyClassCleanup() { }
InBlock.gif        //
InBlock.gif        // 在运行每个测试之前使用 TestInitialize 运行代码 
InBlock.gif        // [TestInitialize()]
InBlock.gif        // public void MyTestInitialize() { }
InBlock.gif        //
InBlock.gif        // 在运行每个测试之后使用 TestCleanup 运行代码
InBlock.gif        // [TestCleanup()]
InBlock.gif        // public void MyTestCleanup() { }
InBlock.gif        //
ExpandedSubBlockEnd.gif        #endregion

InBlock.gif
InBlock.gif        int uid;
InBlock.gif        [TestMethod]
InBlock.gif        public void TestMethod1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            UserFixure userFixure = new UserFixure();
InBlock.gif            Assert.IsTrue(userFixure.ExportTable());            
ExpandedSubBlockEnd.gif        }

InBlock.gif        [TestMethod]
InBlock.gif        public void TestMethod2()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            UserFixure userFixure = new UserFixure();
InBlock.gif            uid = userFixure.Add();
InBlock.gif            Assert.IsTrue(uid>0);
ExpandedSubBlockEnd.gif        }

InBlock.gif        [TestMethod]
InBlock.gif        public void TestMethod3()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            UserFixure userFixure = new UserFixure();
InBlock.gif            Assert.IsTrue(userFixure.Update(uid));
ExpandedSubBlockEnd.gif        }

InBlock.gif        [TestMethod]
InBlock.gif        public void TestMethod4()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            UserFixure userFixure = new UserFixure();
InBlock.gif            Assert.IsTrue(userFixure.Delete(uid));
ExpandedSubBlockEnd.gif        }

InBlock.gif        [TestMethod]
InBlock.gif        public void TestMethod5()
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            UserFixure userFixure = new UserFixure();
InBlock.gif            Assert.IsTrue(userFixure.Query().Count>0);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

11 )在菜单 - 测试 - 加载元数据文件 选择 NHibernateStudy1.vsmdi ,然后按顺序执行 TestMethod1-TestMethod5, 全部成功 !
4. 总结
  通过使用 Nhibernate ,基本上可以使开发人员不在接触繁琐的数据库表和数据库操作代码,您唯一需要关心的就是如何设计好类,让这些类满足您的业务需求。从扩展性来说 Nhinernate 具有非常好的扩展性。与代码生成比较, Nhibernate 更改数据表结构对代码的影响要远远小于代码生成。
如果您想下载Demo:/Files/jillzhang/simle.rar

转载于:https://www.cnblogs.com/erichzhou/archive/2007/03/29/692943.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值