首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

ADO.NET 與 ORM 實戰對比 (二):NHibernate 實作 CRUD 全紀錄

     編輯:關於.NET

NHibernate 為 Java Hibernate 的 .NET 移植版,成熟穩定、支援多資料庫。採 XML 映射檔 (.hbm.xml) 與 POCO 實體類別,屬非侵入式 ORM 代表。

環境建置與必要組件

官網下載 (2.1.2.GA) 解壓後四資料夾:

  • Required_Bins:核心 DLL (NHibernate.dll, Iesi.Collections.dll, log4net.dll 等)
  • Required_For_LazyLoading:延遲載入 Proxy 實現 (Castle/Spring/LinFu 三選一)
  • Configuration_Templates:各資料庫 hibernate.cfg.xml 範本
  • Tests:映射檔範例

專案引用所有 Required_Bins + 選定 Proxy (如 Castle) 組件。

三大設定檔

1. hibernate.cfg.xml (複製到輸出目錄)

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">
      Data Source=zhou;Initial Catalog=AspNetStudy;User ID=sa;Password=jerry;
    </property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="proxyfactory.factory_class">
      NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
    </property>
    <mapping assembly="NHibernateDemo"/>
  </session-factory>
</hibernate-configuration>

2. UserInfo.hbm.xml (嵌入資源)

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    assembly="NHibernateDemo" namespace="NHibernateDemo">
  <class name="UserInfo">
    <id name="UserId" column="UserId"><generator class="native"/></id>
    <property name="UserName"/>
    <property name="RealName"/>
    <property name="Age"/>
    <property name="Sex"/>
    <property name="Mobile"/>
    <property name="Phone"/>
    <property name="Email"/>
  </class>
</hibernate-mapping>

3. POCO 實體類別 (屬性需 virtual、類別非 sealed)

public class UserInfo
{
    public virtual int UserId { get; set; }
    public virtual string UserName { get; set; }
    public virtual string RealName { get; set; }
    public virtual int Age { get; set; }
    public virtual bool Sex { get; set; }
    public virtual string Mobile { get; set; }
    public virtual string Phone { get; set; }
    public virtual string Email { get; set; }
}

CRUD 核心程式碼 (NHibernateCRUD)

public class NHibernateCRUD
{
    private readonly ISessionFactory sessionFactory;

    public NHibernateCRUD()
    {
        sessionFactory = new Configuration().Configure().BuildSessionFactory();
    }

    private ISession GetSession() => sessionFactory.OpenSession();

    public int Count()
    {
        using (var s = GetSession())
        {
            var q = s.CreateQuery("select count(c.UserId) from UserInfo c");
            return (int)q.List<long>()[0];  // Count 回傳 long
        }
    }

    public int Create(UserInfo info)
    {
        using (var s = GetSession())
        {
            int id = (int)s.Save(info);
            s.Flush();
            return id;
        }
    }

    public UserInfo Read(int userId)
    {
        using (var s = GetSession())
            return s.Get<UserInfo>(userId);
    }

    public void Update(UserInfo info)
    {
        using (var s = GetSession())
        {
            s.Update(info);
            s.Flush();
        }
    }

    public void Delete(int userId)
    {
        using (var s = GetSession())
        {
            var q = s.CreateQuery("delete from UserInfo where UserId=:UserId");
            q.SetInt32("UserId", userId);
            q.ExecuteUpdate();
        }
    }

    public void Delete(UserInfo info)
    {
        using (var s = GetSession())
        {
            s.Delete(info);
            s.Flush();
        }
    }

    public int GetMaxUserId()
    {
        using (var s = GetSession())
            return s.CreateQuery("select max(UserId) from UserInfo").List<int>()[0];
    }
}

優缺點評析

  • 優點:消除手寫 SQL/映射代碼,資料庫變更僅調整映射檔與實體,物件導向操作直觀,支援多資料庫、快取機制緩解效能
  • 缺點:底層仍用 ADO.NET,高經驗開發者手寫 SQL 效能更好;千萬級資料量時效能瓶頸明顯;百萬級以下合理使用無虞

NHibernate 適合中型專案、異構資料庫環境、重視維護性與開發速度的團隊。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved