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

NHibernate 是一個功能強大的物件關聯映射 (ORM) 框架,專為搭配 .NET Framework 使用而設計。 它為開發人員提供了一種有效的方式,縮短 .NET 應用程式的物件導向世界與資料庫的關聯世界之間的距離。 透過使用 NHibernate,您可以大幅減少實作資料存取層所需的模板程式碼,讓您的 .NET 應用程式更乾淨、更易維護。
ORM 在簡化資料庫互動中的作用
像 NHibernate 之類的 ORM 框架,透過允許開發人員以物件及其屬性而非 SQL 語句來處理資料,簡化了與關聯式資料庫的互動。 這種抽象可以幫助開發人員更專注於應用程式的商業邏輯,而較少關注底層的 SQL 指令和資料庫架構。 舉例來說,NHibernate 會處理所有 SQL 的產生和執行,讓插入、刪除和更新等作業可以透過簡單的物件轉換和物件操作來進行。
在 .NET 專案中設定 NHibernate
要在您的 .NET 專案中開始使用 NHibernate,第一步是安裝 NHibernate 套件。 您可以透過 Visual Studio 的 NuGet Package Manager,使用下列指令輕鬆完成:
Install-Package 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>
瞭解 NHibernate 的核心元件
NHibernate 的關鍵元件之一是 Session Factory,它是使用工廠設計模式來設計的。 此元件會建立 Session 物件,以管理與資料庫的連線,並持有交易操作。 Session Factory 的建立成本很高,所以通常在每個應用程式生命週期中都會執行一次,因此是效能最佳化的重要元素。
NHibernate 中的關鍵類和方法
NHibernate 圍繞著幾個基本的類別和方法。 例如,ISession 介面在 NHibernate 中發揮基礎性作用,有助於建立資料查詢和操作會話。 類似 OpenSession 的方法可以幫助開發人員啟動交易、執行 SQL 命令以及使用 SQL 語句或 NHibernate 自己的 HQL(Hibernate 查詢語言)查詢資料庫。
使用 NHibernate 將實體映射到資料庫表
NHibernate 中的實體映射是透過映射檔案完成的,通常以 XML 撰寫。 這些檔案通常以實體類命名(例如,Employee.hbm.xml),定義實體的屬性如何映射到資料庫表的欄位。 典型的對應檔案包括類別名稱、表格名稱,以及每個屬性的詳細資訊,包括主索引鍵、欄位名稱和資料類型。
詳細瞭解映射檔案中使用的屬性和屬性。
在這些對應檔案中,您可以為每個屬性指定各種屬性,例如 not-null 約束或唯一約束。 NHibernate 也允許複雜的映射,例如一對多和多對一的關係,提供了一個強大的工具集,用來在物件導向的架構中表示關係資料結構。
在 NHibernate 中執行 SQL 指令和事務。
NHibernate 透過抽象底層 SQL 指令簡化 CRUD (建立、讀取、更新、刪除) 作業。 開發人員無需編寫明確 SQL 程式碼即可執行這些操作,而是使用 ISession 介面提供的方法。 例如,要為資料庫新增一個新實體,只需建立一個物件的新實例,設定其屬性,然後使用 Save 方法。
使用 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");
}
}
}
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
資料庫可移植性與互操作性功能
NHibernate 的設計提供資料庫的可移植性。 由於其方言配置,NHibernate 能夠適應大多數的 SQL 資料庫,只需對程式碼基做最小的變更。 這表示您可以從 SQL Server 轉換到 MySQL 或 Oracle,而無需重寫資料存取層。
為各種資料庫系統(如 SQL Server)適配 NHibernate。
NHibernate 中的 XML 設定檔允許開發人員指定其資料庫系統特有的 SQL 方言。 這使得 NHibernate 成為一個靈活的解決方案,可以輕鬆地與幾乎所有支援 SQL 的關聯式資料庫搭配使用,確保您的應用程式可以在不同的資料庫系統中移植。
使用 IronPDF 的 NHibernate。

整合 NHibernate 與 IronPDF 是一個強大的組合,可以增強您的 .NET 應用程式。 它可以讓您使用 NHibernate 管理資料庫作業,同時利用 IronPDF 從資料產生 PDF 文件。 考慮一種情況,您的應用程式需要提供使用者特定的文件,例如員工報告,這些文件需要以 PDF 格式產生和下載。 NHibernate 可以有效地管理資料庫的資料擷取程序,而 IronPDF 則可以將這些資料轉換成格式良好的 PDF 檔案。
安裝 IronPDF
首先,確保 IronPDF 已加入您的專案。 您可以透過 NuGet Package Manager 安裝 IronPDF 套件來包含它。
Install-Package 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

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

在本教程中,我們探討了 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` 接口抽象化,該接口提供了 Save、Update 和 Delete 等方法。這使開發人員可以在不直接編寫 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 映射文件配置它,以定義數據庫設置和對象映射。



