天天看點

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>