zoukankan      html  css  js  c++  java
  • NHibernate初探(一)简单且完整的示例

    参见Lee的文章http://www.cnblogs.com/lyj/archive/2008/10/30/1323099.html

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

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

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

    (一)  数据库

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

    Customer表结构如下:(version字段用于并发处理的,请参见http://www.cnblogs.com/lyj/archive/2008/10/21/1316269.html

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

    解决方案:NHBSample

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

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

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

    解决方案图示如下:

    (三)  添加实体类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.xsdnhibernate-mapping.xsd文件保存到vs环境

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

    ……\Microsoft Visual Studio 9.0\Xml\Schemas

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

    (1)         hibernate-mapping 这里assembly要添加,namespace也要添加。Assemblydll文件名,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 : Could not compile the mapping document: SelfTest2.Customer.hbm.xml

      ----> 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配置文件

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

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

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

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

     

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

    <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>

    </hibernate-configuration>

     

    可以参考:

    http://nhforge.org/blogs/nhibernate/archive/2008/11/09/nh2-1-0-bytecode-providers.aspx

    (3)         一定要添加<mapping assembly="SelfTest2"/>节。

    (七)添加操作类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<Customer>(customerId);

            }

        }

    名字空间添加:

    using NHibernate;

    (八)  添加测试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;

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

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

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

     

    (2)         Nunit中打开SelfTest2.dll

     

     

    附:解决方案管理器截图

    转载请注明:博客园

    博客园大道至简

    http://www.cnblogs.com/jams742003/

    转载请注明:博客园

  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/jams742003/p/1597446.html
Copyright © 2011-2022 走看看