跳過到頁腳內容
.NET幫助

NHibernate C#(對於開發者的運行原理)

NHibernate C#(開發者使用方法):圖 1 - NHibernate C# Home

NHibernate是一個功能強大的物件關係映射 (ORM) 框架,專為與.NET Framework一起使用而設計。 它為開發人員提供了一種有效的方式來彌合.NET應用程式的物件導向世界和資料庫的關係世界之間的差距。 透過使用 NHibernate,您可以大幅減少實現資料存取層所需的樣板程式碼量,從而使您的.NET應用程式更簡潔、更易於維護。

ORM在簡化資料庫互動中的作用

ORM 框架(例如 NHibernate)簡化了與關聯式資料庫的交互,允許開發人員以物件及其屬性而非 SQL 語句的形式處理資料。 這種抽像有助於開發人員將更多精力集中在應用程式的業務邏輯上,而減少對底層 SQL 命令和資料庫模式的關注。 例如,NHibernate 處理所有 SQL 的產生和執行,允許透過簡單的物件轉換和物件操作來執行插入、刪除和更新等操作。

在.NET專案中設定 NHibernate

要在.NET專案中使用 NHibernate,第一步是安裝 NHibernate 套件。 這可以透過 Visual Studio 的NuGet套件管理器輕鬆完成,使用以下命令:

Install-Package NHibernate

NHibernate C#(開發者使用方法):圖 2 - 開啟命令列控制台並輸入上述命令以安裝 NHibernate

使用 XML 設定檔設定 NHibernate

NHibernate 安裝完成後,下一步就是對其進行設定。 這涉及到創建一個 Hibernate 映射文件,其中詳細說明了資料庫伺服器設定以及物件到資料庫表的映射詳細資訊。 主 XML 檔案通常命名為 hibernate.cfg.xml,其中包含資料庫連接字串、方言和其他資料庫特定設定等設定。

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">
      NHibernate.Connection.DriverConnectionProvider
    </property>
    <property name="connection.driver_class">
      NHibernate.Driver.SqlClientDriver
    </property>
    <property name="connection.connection_string">
      Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
    </property>
    <property name="dialect">
      NHibernate.Dialect.MsSql2012Dialect
    </property>
    <property name="show_sql">true</property>
    <mapping resource="Employee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">
      NHibernate.Connection.DriverConnectionProvider
    </property>
    <property name="connection.driver_class">
      NHibernate.Driver.SqlClientDriver
    </property>
    <property name="connection.connection_string">
      Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
    </property>
    <property name="dialect">
      NHibernate.Dialect.MsSql2012Dialect
    </property>
    <property name="show_sql">true</property>
    <mapping resource="Employee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
XML

了解 NHibernate 的核心元件

NHibernate 的關鍵組件之一是 Session Factory,它是使用工廠設計模式設計的。 此元件會建立 Session 對象,用於管理與資料庫的連接並保存事務操作。 創建會話工廠的成本很高,因此通常每個應用程式生命週期只會創建一次,這使得它成為效能優化的關鍵要素。

NHibernate 中的關鍵類別和方法

NHibernate 的核心是幾個基本的類別和方法。 例如,ISession 介面在 NHibernate 中發揮基礎性作用,有助於建立資料查詢和操作會話。 類似 OpenSession 的方法可以幫助開發人員啟動交易、執行 SQL 命令以及使用 SQL 語句或 NHibernate 自己的 HQL(Hibernate 查詢語言)查詢資料庫。

使用 NHibernate 將實體對應到資料庫表

NHibernate 中的實體映射是透過映射檔案實現的,這些映射檔案通常用 XML 編寫。 這些檔案通常以實體類別命名(例如, Employee.hbm.xml ),定義了實體的屬性如何對應到資料庫表的資料列。 典型的映射檔案包括類別名稱、表名以及每個屬性的詳細信息,包括主鍵、列名和資料類型。

詳細了解映射檔案中使用的屬性和特性

在這些映射檔案中,您可以為每個屬性指定各種屬性,例如非空約束或唯一約束。 NHibernate 還允許複雜的映射,例如一對多和多對一關係,為在物件導向的框架內表示關係資料結構提供了一套強大的工具集。

在 NHibernate 中執行 SQL 指令和事務

NHibernate 透過抽象底層 SQL 指令簡化 CRUD(建立、讀取、更新、刪除)操作。 開發人員無需編寫明確 SQL 程式碼即可執行這些操作,而是使用 ISession 介面提供的方法。 例如,要為資料庫新增一個實體,只需建立一個物件的新實例,設定其屬性,然後使用 Save 方法 ISession

使用 ITransaction 管理交易

NHibernate 中的事務透過 ITransaction 介面進行管理,從而確保資料的完整性和一致性。 使用 BeginTransaction 方法(來自 ISession),開發人員可以確保在將資料提交到資料庫之前所有操作都已成功完成,或在出現問題時回滾,從而維護資料的穩定性。

完整程式碼範例

本範例包括 NHibernate 設定和映射檔案的設置,並示範如何使用 NHibernate 執行建立、讀取、更新和刪除操作。

using NHibernate;
using NHibernate.Cfg;
using System;

// Define the Employee class with virtual properties
public class Employee
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

class Program
{
    private static ISessionFactory sessionFactory;

    static void Main()
    {
        // Initialize the SessionFactory using NHibernate configuration
        sessionFactory = new Configuration().Configure().BuildSessionFactory();

        // Perform database operations
        CreateEmployee();
        ReadEmployee(1);
        UpdateEmployee(1, "UpdatedName");
        DeleteEmployee(1);
    }

    static void CreateEmployee()
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            var newEmployee = new Employee
            {
                FirstName = "Iron",
                LastName = "Software"
            };
            session.Save(newEmployee); // Save the new Employee object to the database
            transaction.Commit(); // Commit the transaction to finalize the insertion
            Console.WriteLine("Employee created: " + newEmployee.Id);
        }
    }

    static void ReadEmployee(int id)
    {
        using (var session = sessionFactory.OpenSession())
        {
            // Retrieve the Employee object by its Id
            var employee = session.Get<Employee>(id);
            Console.WriteLine("Read Employee: " + employee.FirstName + " " + employee.LastName);
        }
    }

    static void UpdateEmployee(int id, string newFirstName)
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            // Get the Employee object by its Id
            var employee = session.Get<Employee>(id);
            employee.FirstName = newFirstName; // Update the employee's first name
            session.Update(employee); // Update the Employee object in the database
            transaction.Commit(); // Commit the transaction to save changes
            Console.WriteLine("Employee updated: " + employee.FirstName);
        }
    }

    static void DeleteEmployee(int id)
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            // Retrieve the Employee object to be deleted
            var employee = session.Get<Employee>(id);
            session.Delete(employee); // Delete the Employee from the database
            transaction.Commit(); // Commit the transaction to finalize the deletion
            Console.WriteLine("Employee deleted");
        }
    }
}
using NHibernate;
using NHibernate.Cfg;
using System;

// Define the Employee class with virtual properties
public class Employee
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

class Program
{
    private static ISessionFactory sessionFactory;

    static void Main()
    {
        // Initialize the SessionFactory using NHibernate configuration
        sessionFactory = new Configuration().Configure().BuildSessionFactory();

        // Perform database operations
        CreateEmployee();
        ReadEmployee(1);
        UpdateEmployee(1, "UpdatedName");
        DeleteEmployee(1);
    }

    static void CreateEmployee()
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            var newEmployee = new Employee
            {
                FirstName = "Iron",
                LastName = "Software"
            };
            session.Save(newEmployee); // Save the new Employee object to the database
            transaction.Commit(); // Commit the transaction to finalize the insertion
            Console.WriteLine("Employee created: " + newEmployee.Id);
        }
    }

    static void ReadEmployee(int id)
    {
        using (var session = sessionFactory.OpenSession())
        {
            // Retrieve the Employee object by its Id
            var employee = session.Get<Employee>(id);
            Console.WriteLine("Read Employee: " + employee.FirstName + " " + employee.LastName);
        }
    }

    static void UpdateEmployee(int id, string newFirstName)
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            // Get the Employee object by its Id
            var employee = session.Get<Employee>(id);
            employee.FirstName = newFirstName; // Update the employee's first name
            session.Update(employee); // Update the Employee object in the database
            transaction.Commit(); // Commit the transaction to save changes
            Console.WriteLine("Employee updated: " + employee.FirstName);
        }
    }

    static void DeleteEmployee(int id)
    {
        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            // Retrieve the Employee object to be deleted
            var employee = session.Get<Employee>(id);
            session.Delete(employee); // Delete the Employee from the database
            transaction.Commit(); // Commit the transaction to finalize the deletion
            Console.WriteLine("Employee deleted");
        }
    }
}
$vbLabelText   $csharpLabel

資料庫可移植性和互通性功能

NHibernate 的設計宗旨就是提供資料庫可攜性。 由於採用了方言配置,NHibernate 只需對程式碼庫進行極少的更改即可適應大多數 SQL 資料庫。 這表示您可以從 SQL Server 切換到 MySQL 或 Oracle,而無需重寫資料存取層。

將 NHibernate 適配到各種資料庫系統,例如 SQL Server

NHibernate 中的 XML 設定檔可讓開發人員指定其資料庫系統特有的 SQL 方言。 這使得 NHibernate 成為一個靈活的解決方案,可以輕鬆適應幾乎任何支援 SQL 的關聯式資料庫,從而確保您的應用程式可以在不同的資料庫系統之間移植。

將 NHibernate 與IronPDF結合使用

NHibernate C#(開發者使用方法):圖 3 - IronPDF主頁

將 NHibernate 與IronPDF整合是一個強大的組合,可以增強您的.NET應用程式。 它允許您使用 NHibernate 管理資料庫操作,同時利用IronPDF從您的資料產生 PDF 文件。 設想這樣一個場景:您的應用程式需要提供使用者特定的文檔,例如員工報告,這些文檔需要以 PDF 格式產生和下載。 NHibernate 可以有效率地管理從資料庫中檢索資料的過程,而IronPDF可以將這些資料轉換為格式良好的 PDF 檔案。

安裝IronPDF

首先,請確保已將IronPDF新增至您的專案。 您可以透過NuGet套件管理器安裝IronPDF套件來包含它。

Install-Package IronPdf

NHibernate C#(開發者使用方法):圖 4 - 透過NuGet套件管理器安裝IronPDF

程式碼範例

讓我們深入探討如何在你的應用程式中實現這一點。 設定好 NHibernate 並從資料庫中檢索必要的資料(例如員工詳細資訊)後,您將準備一個 HTML 模板,該模板表示 PDF 文件應該如何顯示。 此 HTML 範本可使用從 NHibernate 取得的資料動態填充。 例如,如果您要為員工產生報告,則範本將包含員工姓名、ID 和其他相關詳細資訊的佔位符。

以下是一個詳細的程式碼範例,示範如何使用 NHibernate 取得資料並使用IronPDF將其轉換為 PDF:

using IronPdf;
using NHibernate;

static void CreateEmployeeReport(int employeeId)
{
    // Open a session to interact with the database
    using (var session = OpenSession())
    {
        // Retrieve the employee object based on the provided ID
        var employee = session.Get<Employee>(employeeId);

        // Create an instance of the ChromePdfRenderer class from IronPDF
        var renderer = new ChromePdfRenderer();

        // Create the HTML content for the PDF, embedding employee data into the HTML
        var htmlTemplate = $@"
            <html>
            <head>
                <title>Employee Report</title>
            </head>
            <body>
                <h1>Employee Details</h1>
                <p>Name: {employee.FirstName} {employee.LastName}</p>
                <p>ID: {employee.Id}</p>
            </body>
            </html>";

        // Render the HTML string as a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlTemplate);

        // Save the generated PDF to a file
        pdf.SaveAs("EmployeeReport.pdf");
    }
}
using IronPdf;
using NHibernate;

static void CreateEmployeeReport(int employeeId)
{
    // Open a session to interact with the database
    using (var session = OpenSession())
    {
        // Retrieve the employee object based on the provided ID
        var employee = session.Get<Employee>(employeeId);

        // Create an instance of the ChromePdfRenderer class from IronPDF
        var renderer = new ChromePdfRenderer();

        // Create the HTML content for the PDF, embedding employee data into the HTML
        var htmlTemplate = $@"
            <html>
            <head>
                <title>Employee Report</title>
            </head>
            <body>
                <h1>Employee Details</h1>
                <p>Name: {employee.FirstName} {employee.LastName}</p>
                <p>ID: {employee.Id}</p>
            </body>
            </html>";

        // Render the HTML string as a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlTemplate);

        // Save the generated PDF to a file
        pdf.SaveAs("EmployeeReport.pdf");
    }
}
$vbLabelText   $csharpLabel

NHibernate C#(開發者使用方法):圖 5 - 上述程式碼的範例輸出

在這段程式碼中,OpenSession() 是一個初始化 NHibernate 會話的方法,該會話用於獲取員工資料。 IronPDF中的 ChromePdfRenderer 類別隨後取得填充了獲取資料的 HTML 模板,並將其渲染為 PDF。 該 PDF 檔案已儲存到本機,但也可以透過網頁介面直接串流傳輸給使用者。

結論

NHibernate C#(開發者使用方法):圖 6 - IronPDF許可頁面

在本教程中,我們探討了 NHibernate 如何簡化.NET應用程式中的資料庫操作,以及它與IronPDF 的整合如何透過允許產生動態 PDF 文件來增強功能。 NHibernate 提供強大的資料管理工具,而IronPDF提供了一種便捷的方式,可以從填充了資料的 HTML 範本建立專業品質的 PDF。

IronPDF提供免費試用版,授權價格從經濟實惠的價格起,是將強大的 PDF 生成功能整合到您的應用程式中的理想解決方案。 這些工具共同構成了一個全面的資料管理和文件產生解決方案,非常適合企業級專案和小規模專案。

常見問題解答

如何在 C# 中將 NHibernate 集成到 PDF 生成庫中?

NHibernate 可以通過使用其進行數據庫操作和數據檢索來與 IronPDF 集成,這些數據然後可以被 IronPDF 轉換為 PDF 文檔。這使得可以根據用戶特定的數據生成動態 PDF。

NHibernate 中 Session Factory 的目的是什麼?

在 NHibernate 中,Session Factory 是一個關鍵組件,用於創建 Session 對象來管理數據庫連接並進行事務操作。它的創建代價高昂,因此通常在應用程序的生命周期中只實例化一次,以優化性能。

你能解釋一下如何在 NHibernate 中執行 CRUD 操作嗎?

NHibernate 中的 CRUD 操作通過 `ISession` 接口抽象化,該接口提供了 SaveUpdateDelete 等方法。這使開發人員可以在不直接編寫 SQL 命令的情況下執行這些操作。

使用 NHibernate 對 .NET 開發人員有什麼好處?

NHibernate 通過減少數據訪問層所需的樣板代碼來造福 .NET 開發人員,提高應用程序的可維護性。它還抽象了數據庫交互,使開發人員更加專注於業務邏輯。

NHibernate 如何支持數據庫移植性?

NHibernate 通過其方言配置支持數據庫的可移植性,這使其能夠適應各種 SQL 數據庫。這允許開發人員在代碼庫中進行最少更改的情況下從一個數據庫系統轉換到另一個。

NHibernate 中映射文件的作用是什麼?

NHibernate 中的映射文件,通常是 XML 文件,定義了實體的屬性如何映射到數據庫表中的列。它們包含重要的詳細信息,如主鍵、列名稱和數據類型,支持一對多關係等複雜映射。

如何在 NHibernate 中有效地管理事務?

NHibernate 中的事務是通過 `ITransaction` 接口管理的,從而確保數據完整性。開發人員可以使用 `ISession` 的 BeginTransaction 方法進行操作,只有在所有操作成功時才提交數據,如果有任何問題則回滾。

如何在 .NET 項目中設置 NHibernate?

要設置 NHibernate,通過 Visual Studio 的 NuGet 程式包管理器使用命令 Install-Package NHibernate 安裝它。使用像 `hibernate.cfg.xml` 這樣的 XML 映射文件配置它,以定義數據庫設置和對象映射。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me