跳至頁尾內容
開發者更新

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

NHibernate C# (它如何為開發者工作):圖1 - NHibernate C# 首頁

NHibernate 是一個強大的物件關係對應 (ORM) 框架,為.NET框架設計。 它提供開發者一種高效的方法來橋接.NET應用程式的物件導向世界和資料庫的關聯世界之間的鴻溝。 通過使用NHibernate,您可以顯著減少實現資料存取層所需的樣板程式碼量,從而使您的.NET應用程式更乾淨和更易於維護。

ORM在簡化資料庫交互中的角色

像NHibernate這樣的ORM框架通過允許開發者用物件及其屬性而不是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物件。 Session Factory的建立成本高,所以通常在每個應用程式的生命週期中只建立一次,這使其成為性能優化的重要元素。

NHibernate中的關鍵類別和方法

NHibernate圍繞著幾個基本類別和方法。 例如,ISession介面在NHibernate中起著基礎作用,促進資料查詢和操作會話的建立。 像OpenSession這樣的方法幫助開發者開始交易,執行SQL命令,以及使用SQL語句或NHibernate自己的HQL(宿主查詢語言)查詢資料庫。

使用NHibernate將實體映射到資料庫表

在NHibernate中,實體映射是通過映射文件來實現的,這些文件通常用XML編寫。 這些文件,通常以實體類(例如,Employee.hbm.xml)命名,定義實體的屬性如何映射到資料表的欄位。 典型的映射文件包括類名、表名以及每個屬性的詳細資訊,包括主鍵、列名和資料型別。

詳解映射文件中使用的屬性和屬性

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

在NHibernate中執行SQL命令和事務

NHibernate通過抽象底層的SQL命令簡化了CRUD(建立、讀取、更新、刪除)操作。 開發者可以在不編寫顯式SQL程式碼的情況下執行這些操作,而是使用ISession介面提供的方法。 例如,要將新實體新增到資料庫,只需建立物件的新實例,設置其屬性,並使用ISession

使用ITransaction管理事務

在NHibernate中,事務是通過ITransaction介面管理的,它確保了資料的完整性和一致性。 通過使用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");
        }
    }
}
Imports NHibernate
Imports NHibernate.Cfg
Imports System

' Define the Employee class with virtual properties
Public Class Employee
	Public Overridable Property Id() As Integer
	Public Overridable Property FirstName() As String
	Public Overridable Property LastName() As String
End Class

Friend Class Program
	Private Shared sessionFactory As ISessionFactory

	Shared Sub Main()
		' Initialize the SessionFactory using NHibernate configuration
		sessionFactory = (New Configuration()).Configure().BuildSessionFactory()

		' Perform database operations
		CreateEmployee()
		ReadEmployee(1)
		UpdateEmployee(1, "UpdatedName")
		DeleteEmployee(1)
	End Sub

	Private Shared Sub CreateEmployee()
		Using session = sessionFactory.OpenSession()
		Using transaction = session.BeginTransaction()
			Dim newEmployee = New Employee With {
				.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)
		End Using
		End Using
	End Sub

	Private Shared Sub ReadEmployee(ByVal id As Integer)
		Using session = sessionFactory.OpenSession()
			' Retrieve the Employee object by its Id
			Dim employee = session.Get(Of Employee)(id)
			Console.WriteLine("Read Employee: " & employee.FirstName & " " & employee.LastName)
		End Using
	End Sub

	Private Shared Sub UpdateEmployee(ByVal id As Integer, ByVal newFirstName As String)
		Using session = sessionFactory.OpenSession()
		Using transaction = session.BeginTransaction()
			' Get the Employee object by its Id
			Dim employee = session.Get(Of 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)
		End Using
		End Using
	End Sub

	Private Shared Sub DeleteEmployee(ByVal id As Integer)
		Using session = sessionFactory.OpenSession()
		Using transaction = session.BeginTransaction()
			' Retrieve the Employee object to be deleted
			Dim employee = session.Get(Of Employee)(id)
			session.Delete(employee) ' Delete the Employee from the database
			transaction.Commit() ' Commit the transaction to finalize the deletion
			Console.WriteLine("Employee deleted")
		End Using
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

資料庫可移植性和互操作性特性

NHibernate的設計初衷就是為了提供資料庫可移植性。 由於其方言配置,NHibernate可以在對程式碼庫進行最小更改的情況下適應大多數SQL資料庫。 這意味著您可以從SQL伺服器切換到MySQL或Oracle,而無需重寫資料存取層。

將NHibernate適應於各種資料庫系統如SQL伺服器

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");
    }
}
Imports IronPdf
Imports NHibernate

Shared Sub CreateEmployeeReport(ByVal employeeId As Integer)
	' Open a session to interact with the database
	Using session = OpenSession()
		' Retrieve the employee object based on the provided ID
		Dim employee = session.Get(Of Employee)(employeeId)

		' Create an instance of the ChromePdfRenderer class from IronPDF
		Dim renderer = New ChromePdfRenderer()

		' Create the HTML content for the PDF, embedding employee data into the HTML
		Dim 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
		Dim pdf = renderer.RenderHtmlAsPdf(htmlTemplate)

		' Save the generated PDF to a file
		pdf.SaveAs("EmployeeReport.pdf")
	End Using
End Sub
$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生成功能。 這些工具一起提供了管理資料和生成文件的全面解決方案,適合企業級和小型專案。

常見問題

如何將 NHibernate 與 C# 中的 PDF 生成程式庫整合?

NHibernate 可以通過使用 NHibernate 處理資料庫操作並檢索資料,然後由 IronPDF 將其轉換為 PDF 文件來與 IronPDF 整合。這樣可以根據使用者特定資料生成動態 PDF。

NHibernate 中的 Session Factory 的用途是什麼?

在 NHibernate 中,Session Factory 是一個重要的組件,它建立 Session 物件以管理資料庫連接和進行事務操作。它透過建立昂貴且通常在應用程式生命週期中僅實例化一次來優化效能。

您能解釋 NHibernate 中的 CRUD 操作是如何進行的嗎?

NHibernate 中的 CRUD 操作透過 `ISession` 介面抽象化,該介面提供方法如 SaveUpdateDelete。這允許開發者進行這些操作而無需直接編寫 SQL 指令。

using NHibernate 對 .NET 開發者有什麼好處?

NHibernate 為 .NET 開發者帶來了許多好處,如減少資料存取層的樣板程式碼,提高應用程式的可維護性。它還抽象化了資料庫交互,允許開發者更多地專注於業務邏輯。

NHibernate 如何支持資料庫可移植性?

NHibernate 透過其方言配置支持資料庫可移植性,使其能夠適應各種 SQL 資料庫。這使開發者可以在幾乎不更改程式碼庫的情況下從一個資料庫系統切換到另一個。

NHibernate 中映射文件的角色是什麼?

NHibernate 中的映射文件,通常是 XML 文件,定義了一個實體的屬性如何映射到資料庫表中的欄。它們包括重要細節,如主鍵、欄名稱和資料型別,支持一對多關系等複雜映射。

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

在 NHibernate 中,事務是通過 `ITransaction` 介面來管理的,這確保了資料的完整性。開發者可以使用 `ISession` 的 BeginTransaction 方法來處理操作,只有在所有操作成功時才提交資料,否則在發生任何問題時回滾。

如何在 .NET 專案中設置 NHibernate?

要設置 NHibernate,使用 Visual Studio 的 NuGet Package Manager 安裝 NHibernate 包,使用命令 Install-Package NHibernate。用類似 `hibernate.cfg.xml` 的 XML 映射文件配置它,以定義資料庫設置和物件映射。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話