天天看点

NHibernate初探(一)简单且完整的示例

的第一个例子,一步步的跟着做,终于做出来一个。——!

这里我把这个例子简化一下,在同一个项目里进行。

我的环境为:vs2008+win2003 server+mssql2000 +.net 3.5

(一)  数据库

这里我用的还是SelfTest数据库。新加的Customer客户表

NHibernate初探(一)简单且完整的示例

(二)  新建空解决方案,并新建类库项目

解决方案:NHBSample

在解决方案中添加两个类库

(1)       Shared类库,用于存放要引入的库文件(方便于管理与引用)

(2)       SelfTest类库,这个类库包含所有的数据(包括测试)

解决方案图示如下:

NHibernate初探(一)简单且完整的示例

(三)  添加实体类Customer

在SelfTest2类库中添加Customer类

public class Customer

    {

        public virtual int Unid { get; set; }

        public virtual string FirstName { get; set; }

        public virtual string LastName { get; set; }

}

注意:这里属性要为virtual。就会出否则出现无效的代理类型异常。

现在把Unid的虚修饰符去掉,这里我在vs打印窗口找了一段信息如下:

……

InvalidProxyTypeException : The following types may not be used as proxies:

SelfTest2.Customer: method get_Unid should be 'public/protected virtual' or 'protected internal virtual'

SelfTest2.Customer: method set_Unid should be 'public/protected virtual' or 'protected internal virtual'

(四)  添加实体类的Mapping(映射)

为Customer类添加映射。文件名也叫Customer(全名:Customer.hbm.xml)吧!

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="SelfTest2" namespace="SelfTest2">

  <class name="Customer">

    <id name="Unid" column="CustomerId">

      <generator class="native"></generator>

    </id>

    <property name="FirstName" column="firstname"></property>

    <property name="LastName" column="LastName"></property>

  </class>

</hibernate-mapping>

提示:

为了出现智能提示,可以把

configuration.xsd和nhibernate-mapping.xsd文件保存到vs环境

安装目录(我的是vs2008,就是9.0):

……\Microsoft Visual Studio 9.0\Xml\Schemas

注意:这里有几个要注意的地方

(1)         hibernate-mapping 这里assembly要添加,namespace也要添加。Assembly为dll文件名,namespace为实体类(Customer)的名字空间名。

如果不添加assembly名,则会出现映射异常,(程序集未指定)。如下信息:

NHibernate.MappingException : Could not compile the mapping document: SelfTest2.Customer.hbm.xml

  ----> NHibernate.MappingException : persistent class SelfTest2.Customer not found

  ----> System.TypeLoadException : Could not load type SelfTest2.Customer. Possible cause: no assembly name specified.

如果不指定名字空间名则也会出现映射异常,(不能加载实体类),如下信息:

  ----> NHibernate.MappingException : persistent class Customer, SelfTest2 not found

  ----> System.TypeLoadException : 未能从程序集“SelfTest2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“Customer”。

(2)         类的属性名要与Customer实体类中的名字相同(敏感),列名不敏感

(五)  创建辅助类NHBHelper

在SelfTest2类库中添加类:NHBHelper

用于从ISessionFactory中获取一个ISession(NHibernate的工作单元),如下:

public class NHBHelper

        private ISessionFactory _sessionFactory;

        public NHBHelper()

        {

            _sessionFactory = GetSessionFactory();

        }

        private ISessionFactory GetSessionFactory()

            return (new Configuration()).Configure("NHibernate.cfg.xml").BuildSessionFactory();

        public ISession GetSession()

            return _sessionFactory.OpenSession();

这里所用到的名字空间为:

using NHibernate.Cfg;

using NHibernate;

在这个类库中添加引用:NHibernate.dll(从本解决方案中的另一个类库中选择)

这里一起把用到的库引入好了:

NHibernate初探(一)简单且完整的示例

(六)  添加NHibernate配置文件

文件名为:hibernate.cfg.xml(因为辅助类NHBHelper中要读取这个文件,我把这个文件放到了bin\debug中(注意路径))

因为现在用的是mssql2000,所以从

NHibernate-2.1.1.GA-src\src\NHibernate.Config.Templates

找到MSSQL.cfg.xml文件,改改

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

  <session-factory name="SelfTest2">

    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

    <property name="connection.connection_string">Server=.;initial catalog=selftest;uid=sa;pwd=***;</property>

    <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>

    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

    <mapping assembly="SelfTest2"/>

  </session-factory>

</hibernate-configuration>

这里有几点注意:

(1)数据库连接串

(2)代理属性这里<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

现在这里用的是Castle代理,所以库要添加对

NHibernate.ByteCode.Castle.dll

的引用。否则会出现异常。

贴出castle代理的session-factory最简配置:

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >

    <session-factory name="YourAppName">

        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>

        <property name="connection.connection_string">

            Server=(local);initial catalog=nhibernate;Integrated Security=SSPI

        </property>

        <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

    </session-factory>

可以参考:

<a href="http://nhforge.org/blogs/nhibernate/archive/2008/11/09/nh2-1-0-bytecode-providers.aspx" target="_blank">http://nhforge.org/blogs/nhibernate/archive/2008/11/09/nh2-1-0-bytecode-providers.aspx</a>

(3)         一定要添加&lt;mapping assembly="SelfTest2"/&gt;节。

(七)添加操作类NHBDo

用于业务逻辑,在本类库添加新类NHBDo.cs

public class NHBDo

        protected ISession Session { get; set; }

        public NHBDo(ISession session)

            Session = session;

        public void CreateCustomer(Customer customer)

            Session.Save(customer);

            Session.Flush();

        public Customer GetCustomerById(int customerId)

            return Session.Get&lt;Customer&gt;(customerId);

    }

名字空间添加:

(八)  添加测试Test

在本类库添加新类Test.cs

用于测试。

[TestFixture]

    public class Test

        NHBDo ddo;

        NHBHelper helper;

        [TestFixtureSetUp]

        public void Create()

            helper = new NHBHelper();

            ddo = new NHBDo(helper.GetSession());

        [Test]

        public void TestGetOne()

        {         

            Customer customer=ddo.GetCustomerById(1);

            string s=customer.FirstName;

            //Assert.AreEqual(1, customerId);

引用名字空间:

using NUnit.Framework;

(1)在TestGetOne方法测试,信息窗口输出:

------ Test started: Assembly: SelfTest2.dll ------

1 passed, 0 failed, 0 skipped, took 4.69 seconds (NUnit 2.5.0).

(2)         Nunit中打开SelfTest2.dll

NHibernate初探(一)简单且完整的示例

附:解决方案管理器截图

NHibernate初探(一)简单且完整的示例

转载请注明:博客园

博客园大道至简

<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>