我的NHibernate曲折之行

來源:互聯網
上載者:User

標籤:winform   style   blog   http   io   color   os   ar   使用   

之前,看過很多NHibernate的東西。特別是 YJingLee的NHibernate之旅系列比較經典。看得多了,但是還沒有真正的從頭到尾的做過一邊。今天從頭到尾做了一遍,發現問題還真多。我就將我做的過程和在這中間碰到的問題跟大家分享一下。也可以讓一些初學的朋友少走一些彎路,當然我碰到的很多問題在網上都能找到答案,我也就將一些需要注意點,和出錯的點收集一下,然後放到一起,節省大家時間去瘋狂Google。大致過程參照YJingLee的NHibernate之旅(2):第一個NHibernate程式。不過YJingLee用的是NUnit測試架構,我這裡直接用了一個Windows Form項目來做測試。
     我用的開發環境:Visual Studio 2008SP1+SQL Server 2008 + NHibernate-2.1.0.GA最新版。
     首先建立一個空的解決方案,命名為NHibernateSimpale,然後建立三個項目分別為DAL類庫項目,Model項目,NHibernateTest表單項目。
     然後刪除掉自動產生的Class1.cs.



     我這裡為了示範這個流程,就只建立了一個最簡單的資料庫,在文章的末尾我會提供將原始碼和資料庫執行指令碼下載。
     我建立了一個NHibernate資料庫,然後建立三張表,經典的Student,Course,StudentCourse。其實真正用到了就一張表Student。
     我這裡使用的O/R Mapping的工具是mygeneration。我將其產生的對應檔和實體類檔案的兩個檔案夾Entities和Mappings拷貝至Model檔案夾下面,然後將其包含進項目中。這裡注意了,第一個問題出現了,我當時在產生對應檔的時候在另外一個路徑下,所以產生的預設的命名空間需要改成我現在的Model.Entities的命名空間。   
    在NHibernateTest裡面添加三個設定檔,App.config,NHibernateMSSQL.config,NHibernateOracle.config其中第一個是用來存放資料庫的連結字串的,當然後別的用途。第二個,第三個是用來做NHibernate的設定檔的。這裡我是為了實現多資料庫的NHibernate的支援。可以讓程式有一個比較好的資料庫的擴充性。下次如果要從MSSQL換成Oracle或者MYSql只要修改或者增加一個設定檔就OK。
    在DAL項目中添加兩個類,GetStudent.cs,SessionManager.cs,第一個是用來擷取學生資訊的。第二個是用來管理NHibernate中的Session,可以說相當於一個協助類。
   經過以上步驟得到如下的結果。當然是沒有任何代碼的。
     
  
接下來先檢查Student.hbm.xml中的

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Model.Entities.Student,Model" table="Student" lazy="true">
    <id name="StudentId" column="StudentId" type="int">
      <generator class="native" />
    </id>
    <property type="string" length="40" name="StudentName" column="[StudentName]" />
    <property type="string" length="20" name="StudentPassword" column="[StudentPassword]" />
    <property type="string" length="40" name="EmailAddress" column="[EmailAddress]" />
    <property type="DateTime" name="DateCreated" column="[DateCreated]" />
  </class>
</hibernate-mapping>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Model.Entities.Student,Model" table="Student" lazy="true">

這裡要注意是2.2,不是2.0。
其次是在下面的Model.Entities.Student,Model這裡前者是實體,後者是程式集。這個當然只有初學者會有點疑問。

接下來是增加應用程式設定檔資訊,首先是在App.config裡面加上

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <!--<add name="Connection String" connectionString="Data Source=YeanJay;User Id=YeanJay;Password=YeanJay;Persist Security Info=true" providerName="System.Data.OracleClient"/>-->
        <add name="Connection String" connectionString="Data Source=YeanJay;Database=NHibernate;uid=YeanJay;pwd=YeanJay" providerName="System.Data.SqlClient"/>

    </connectionStrings>
</configuration>

這裡只是增加了資料庫連結字串,注意:這裡的Connection String在NHibernate的設定檔中要用到,所以要保持一致。這裡如果要將資料庫從MSSql遷移到Oracle,那麼我們只要將上面的注釋去掉,然後將下面這句MSSQL的注釋掉就可以了。
然後來看NHibernate的兩個設定檔:NHibernateMSSQL.config和NHibernateOracle.config
 >NHibernateMSSQL.config:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="northwind">
        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string_name">Connection String</property>
        <property name="connection.isolation">ReadCommitted</property>
         <!-- Mapping Files -->
        <mapping assembly="Model"/>
    </session-factory>
</hibernate-configuration>


>NHibernateOracle.config


<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="northwind">
        <property name="dialect">NHibernate.Dialect.Oracle10Dialect</property>
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
        <property name="connection.connection_string_name">Connection String</property>
        <property name="connection.isolation">ReadCommitted</property>

        <!-- Mapping Files -->
        <mapping assembly="Model"/>
    </session-factory>
</hibernate-configuration>

這裡有一個<mapping assembly="Model">就是之前提到的那個映射實體類的那個程式集。
在開始編寫代碼之前,我們需要將一些需要的引用添加到每個工程裡面:
DAL:引用Model項目和NHibernate.dll
Model:引用Iesi.Collections.dll和NHibernate.dll
在WinForm項目中:根據YJingLee的例子是引用DAL,Model這兩個項目,和NHibernate.dll,暫時我們也這麼引用。
現在開始編寫代碼:
SessionManager.cs類:

Code

     這裡的Configuration ctg = new Configuration().Configure("./NHibernateMSSQL.config");的方式在NHibernate的靈活配置 有講到。
     當然這裡的"./NHibernateMSSQL.config"在實際生產中一般不要寫到這裡來,一般是從設定檔中讀取過來。這裡為了方便,我就直接寫在這裡了。
     這裡我也沒有去關心這個安全執行緒不安全的問題了。見諒!

 SessionManager.cs類:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using Model.Entities;
//using NHibernate.Cfg;

namespace DAL {
   public class GetStudent {
       private ISession _session;

       public ISession Session {
           set { _session = value; }
       }

       public GetStudent(ISession session) {
           _session = session;
       }

       public Student GetStudentById(int studentId) {
           return _session.Get<Student>(studentId);
       }
   }
}

     
Form.cs 代碼:

Code

OK,開始執行。
叮!第一個錯誤跳出來:
“NHibernate.Cfg.Configuration”的類型初始值設定項引發異常。
查看詳細資料:
未能負載檔案或程式集“log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821”或它的某一個依賴項。
系統找不到指定的檔案。

第一次想到在DAL中加入log4net.dll(這個dll在下載過來的最新版的NHibernate的bin檔案夾下有的)。沒想到問題依然存在,那好,就先撤銷在DAL中的log4net,然後直接到Winform下添加log4net結果錯誤消失了。但是第二個錯誤 咚!又出來了!


The following types may not be used as proxies:

Model.Entities.Course:method get_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Course: method set_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Course: method get_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Course: method set_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Course: method Clone should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.StudentCourse: method get_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.StudentCourse: method set_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘


Model.Entities.StudentCourse: method get_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.StudentCourse: method set_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.StudentCourse: method Clone should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Student: method get_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Student: method set_IsDeleted should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Student: method get_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Student: method set_IsChanged should be ‘public/protected virtual‘ or ‘protected internal virtual‘

Model.Entities.Student: method Clone should be ‘public/protected virtual‘ or ‘protected internal virtual‘


    這個就是在老趙今天發的我對NHibernate的感受(2):何必到處都virtual的提到的到處都是Virtual了,在MyGeneration產生的對應檔中,有些方法並不是Virtural的,所以會出現編譯通過,但是執行出錯的情況。
   解決方案,當然是在每個方法和屬性上面加上Virtual了。

處理完這個錯誤,當然還是沒有那麼順利就過關啦,第三個錯誤依舊報來!

這也就是需要注意的另外一點:在2.1版本中的NHibernate中需要在NHibernate設定檔中加入
<property name=‘proxyfactory.factory_class‘>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
這樣一節,這個來源於YJingLee部落格裡的一個回覆。

加入以後,繼續編譯,執行。叮叮!!又來一錯誤:

“NHibernate.ByteCode.Castle.ProxyFactory”的類型初始值設定項引發異常。
查看詳細資料:
未能負載檔案或程式集“Castle.DynamicProxy2, Version=2.1.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc”或它的某一個依賴項。
系統找不到指定的檔案。
當然應該也是2.1的版本的緣故咯。然後繼續到源碼檔案夾下的bin目錄下找到這個DLL,添加。具體資訊可以參考這裡。
 繼續編譯執行。繼續出錯:

未能負載檔案或程式集“Castle.Core, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc”或它的某一個依賴項。系統找不到指定的檔案。

神呐,繼續找問題,繼續添加引用。
繼續編譯。現在發現在Winform下的引用已經很多了。都是NHibernate2.1執行的依賴項。
全部添加完,相變的引用如下:

這些引用都可以在NHibernate源碼的bin目錄下可以找到。
接下來編譯。測試通過!!!
執行的介面如下:


資料庫執行指令碼下載,項目原始碼下載。

我的NHibernate曲折之行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.