了解ORM
首先來解釋下ORM對象關系映射(Object Relational Mapping),是一種為了解決面向對象與關系數據庫存在的互不匹配的現象的技術。
一般以第三方插件的形式,在程序中調用。
ORM是通過使用描述對象和數據庫之間映射的元數據,將程序中的對象自動持久化到關系數據庫中。本質上就是將數據從一種形式轉換到另一種形式。
這里解釋下
數據持久化:就是將內存中的數據模型轉換為存儲模型,以及將存儲模型轉換為內存中的數據模型的統稱。在應用程序中能永久地保存各個處理狀態信息的機制。如果沒有持久化這個機制,狀態只能保存在內存中,機器關機后就會丟失。
NHibernate就是用於做數據持久化相關的編程工作,能夠使開發人員從原來枯燥的SQL語句的編寫中解放出來,解放出來的精力可以讓開發人員投入到業務邏輯的實現。
NHibernate的使用
一、NHibernate簡介
一個Java開源項目Hibernate發展來的NHibernate。與數據庫打交道主要是用NHibernate,NHibernate的開發者嘗試為其提供與Hibernate類似的API。
二、NHibernate下載
使用前我們需要下載Nhibernate,下載地址:http://sourceforge.net/projects/nhibernate/files/NHibernate/。
NHibernate-3.3.3.GA-src.zip 是源文件,里面有源代碼。
NHibernate-3.3.3.GA-bin.zip 是使用文件,解壓后能直接使用的dll。
在接下的實例中,使用的NHibernate-3.3.3GA版本
三、NHibernate相關的電子書
NHibernate 3.0 CookBook介紹:http://www.cnblogs.com/lyj/archive/2010/10/11/nhibernate-3-0-cookbook.html
NHibernate 3.0 CookBook電子書下載地址:http://files.cnblogs.com/lyj/Packtpub.NHibernate.3.0.Cookbook.Oct.2010.zip
原書示例代碼下載地址:http://downloads.packtpub.com/sites/default/files/3043_code.zip
四、NHibernate的使用步驟
1.在數據庫中創建把.NET類持久化的對應表
2.創建需求被持久化的.net類
3.創建映射文件,告訴NHibernate怎么樣持久化這些類
4.創建NHibernate的配置文件,以告訴NHibernate怎么樣連接數據庫
5.使用NHibernate提供的API
從別的的博客中看到NHibernate3.3的使用過程,自己重新試做了一次,按上述用步驟操作如下:
第一步、在數據庫中創建把.net類持久化的對應表
這里選用的是數據庫示例的Northwind數據庫,需要持久化的表是Customers

Customers表中有以下的列

現在需要持久化的Customers表有了,接下來去創建要被持久化的類。
第二步、創建需求被持久化的.net類
首先用Visual Studio2010 新建一個asp.net空web應用程序。在UI界面中添加一個GridView控件,用於最后數據呈現。附上WebForm1.aspx中代碼:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NHibernateUI.WebForm1" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title></title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 <asp:GridView ID="GridView1" runat="server"> 13 </asp:GridView> 14 </div> 15 </form> 16 </body> 17 </html>
然后創建兩個類庫文件,一個命名為NHibernate.Domain,另一個命名為NHibernate.DataPortal。
最后所有添加的文件如下圖所示:

在NHibernate.Domain中添加一個Customer.cs類文件,這個類,就是我們需要持久化的類。Customer.cs中代碼如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace NHibernate.Domain.Entities 7 { 8 [Serializable] 9 public class Customer 10 { 11 #region Customer 12 public virtual string CustomerID { get; set; } 13 public virtual string CompanyName { get; set; } 14 public virtual string ContactName { get; set; } 15 public virtual string ContactTitle { get; set; } 16 public virtual string Address { get; set; } 17 public virtual string City { get; set; } 18 public virtual string Region { get; set; } 19 public virtual string PostalCode { get; set; } 20 public virtual string Country { get; set; } 21 public virtual string Phone { get; set; } 22 public virtual string Fax { get; set; } 23 #endregion 24 } 25 }
第三步、創建映射文件,告訴NHibernate怎么樣持久化這些類
然后在NHibernate.Domain中添加一個Xml文件,Customer.hbm.xml,命名規則是“需要持久化類名.hbm.xml”,配置此實體類對應的映射文件。
1 <?xml version="1.0" encoding="utf-8" ?> 2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate.Domain" namespace="NHibernate.Domain.Entities"> 3 <class name="NHibernate.Domain.Entities.Customer,NHibernate.Domain" table="Customers"> 4 <id name="CustomerID" column="CustomerID" type="string" unsaved-value="0"> 5 <generator class="increment"/> 6 </id> 7 <property name="CompanyName" column="CompanyName" type="string" /> 8 <property name="ContactName" column="ContactName" type="string" /> 9 <property name="ContactTitle" column="ContactTitle" type="string" /> 10 <property name="Address" column="Address" type="string" /> 11 <property name="City" column="City" type="string" /> 12 <property name="Region" column="Region" type="string" /> 13 <property name="PostalCode" column="PostalCode" type="string" /> 14 <property name="Country" column="Country" type="string" /> 15 <property name="Phone" column="Phone" type="string" /> 16 <property name="Fax" column="Fax" type="string" /> 17 18 </class> 19 </hibernate-mapping>
注意:
在這個Customer.hbm.xml映射文件中,一定要把“生成操作”設置成:嵌入的資源
XML文件的默認生成操作為“內容”,這里需要修改為“嵌入的資源”生成,否則出現“ failed: NHibernate.MappingException : No persister for: NHibernateSample.Domain.Entities.Customer”異常。

在NHibernate.DataPortal的引用中,添加上Nhibernate文件中的Iesi.Collections.dll和NHibernate.dll。以及NHibernate.Domain生成的NHibernate.Domain.dll文件。

編寫操作類
然后在NHibernate.DataPortal的CustomerDal.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NHibernate.Domain.Entities; namespace NHibernate.DataPortal { public class CustomerDal { private NHibernateHelper nhibernateHelper = new NHibernateHelper(); protected ISession Session { get;set;} public CustomerDal() { this.Session = nhibernateHelper.GetSesion(); } public CustomerDal(ISession session) { this.Session = session; } public void CreateCustomer(Customer customer) { Session.Save(customer); Session.Flush(); } public Customer GetCustomerById(int customerId) { return Session.Get<Customer>(customerId); } public IList<Customer> GetCustomers() { IList<Customer> list = null; list = Session.QueryOver<Customer>().List(); return list; } } }
編寫數據庫訪問層
NHibernateHelper.cs文件:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NHibernate.Cfg; namespace NHibernate.DataPortal { public class NHibernateHelper { private ISessionFactory _sessionFactory; public NHibernateHelper() { _sessionFactory = GetSessionFactory(); } private ISessionFactory GetSessionFactory() { return (new Configuration()).Configure().BuildSessionFactory(); } public ISession GetSesion() { return _sessionFactory.OpenSession(); } } }
第四步、創建NHibernate的配置文件,以告訴NHibernate怎么樣連接數據庫
hibernate.cfg.xml文件:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <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">Server=.;initial catalog=northwind;Integrated Security=True</property> <property name="proxyfactory.factory_class">NHibernate.Bytecode.DefaultProxyFactoryFactory,NHibernate</property> <property name="show_sql">true</property> <property name="command_timeout">10</property> <property name="adonet.batch_size">10</property> <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> <mapping assembly="NHibernate.Domain" /> </session-factory> </hibernate-configuration>
這個hibernate.cfg.xml文件中,需要將“復制到輸出目錄”設置成“始終復制”
注意:
XML文件的默認“復制到輸出目錄”為“不復制”,這里需要修改為“始終復制”。否則出現“failed: NHibernate.Cfg.HibernateConfigException : An exception occurred during configuration of persistence layer. ----> System.IO.FileNotFoundException : 未能找到文件“NHibernateSample\NHibernateSample.Data.Test\bin\Debug\hibernate.cfg.xml””異常。
第五步、使用NHibernate提供的API
在編寫前面的操作類中已經使用了Nhibernate提供的SessionFactory。
最后在WebForm1.aspx中調用操作類的方法
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace NHibernateUI { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { NHibernate.DataPortal.CustomerDal customerDal = new NHibernate.DataPortal.CustomerDal(); GridView1.DataSource = customerDal.GetCustomers(); GridView1.DataBind(); } } } }
顯示結果如下:

這次主要是對Nhibernate的一個初步的使用,具體實現細節,在后續的學習中去了解。
以上內容參考了一些Nhibernate不錯的博文。
http://www.cnblogs.com/lyj/archive/2008/10/14/1310913.html
http://www.cnblogs.com/stone_w/archive/2011/09/15/2177830.html
http://www.cnblogs.com/cpine/archive/2013/05/04/NHibernate%E9%85%8D%E7%BD%AE.html
