.NET幫助 NHibernate C#(對於開發者的運行原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article NHibernate 是一個強大的物件關聯映射(ORM)框架,專為 .NET 框架使用而設計。 它為開發人員提供了一種有效的方法,將 .NET 應用程式的物件導向世界和資料庫的關聯世界連接起來。 通過使用 NHibernate,您可以顯著減少實現資料訪問層所需的樣板代碼,使您的 .NET 應用程式更加整潔和易於維護。 ORM 在簡化資料庫交互中的作用 像 NHibernate 這樣的 ORM 框架通過允許開發者以物件及其屬性而非 SQL 語句的形式與關聯資料庫進行交互,簡化了與關聯資料庫的交互。 這種抽象幫助開發者更多地專注於應用程式的業務邏輯,而不是底層的 SQL 命令和資料庫模式。 例如,NHibernate 處理所有的 SQL 生成和執行,允許通過簡單的物件轉換和物件操作進行諸如插入、刪除和更新等操作。 在 .NET 專案中設置 NHibernate 要在您的 .NET 專案中開始使用 NHibernate,第一步是安裝 NHibernate 封裝。 這可以通過 Visual Studio 的 NuGet 封裝管理器使用以下命令輕鬆完成: 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> XML 了解 NHibernate 的核心組件 NHibernate 的核心組件之一是會話工廠,它是使用工廠設計模式設計的。 這個組件創建管理資料庫連接的會話對象並持有事務操作。 會話工廠的創建成本很高,因此通常在應用程式的生命週期中僅創建一次,使其成為性能優化的重要因素。 NHibernate 中的關鍵類和方法 NHibernate 圍繞幾個重要的類和方法。 例如,ISession 介面在 NHibernate 中扮演著基本角色,促進了數據查詢和操作會話的建立。 像 OpenSession 這樣的方法幫助開發人員開始事務,執行 SQL 命令,並使用 SQL 語句或 NHibernate 自己的 HQL(Hibernate 查詢語言)查詢資料庫。 將實體映射到 NHibernate 的資料庫表 NHibernate 中的實體映射通過映射文件完成,通常使用 XML 編寫。 這些文件通常以實體類命名(例如,Employee.hbm.xml),定義實體屬性如何映射到資料庫表的列。 一個典型的映射文件包括類名、表名和每個屬性的詳情,包括主鍵、列名和數據類型。 對映射文件中使用的屬性和屬性的詳細了解 在這些映射文件中,你可以為每個屬性指定各種屬性,比如非空約束或唯一約束。 NHibernate 還允許進行複雜的映射,如一對多和多對一的關係,為在物件導向框架中表示關係數據結構提供了一個強大的工具集。 在 NHibernate 中執行 SQL 命令和事務 NHibernate 通過抽象底層的 SQL 命令簡化了 CRUD(創建、讀取、更新、刪除)操作。 開發人員可以不必編寫明確的 SQL 代碼,而是使用 ISession 介面提供的方法來執行這些操作。 例如,要向資料庫添加新的實體,你只需創建一個該對象的新實例,設置其屬性,然後使用 ISession 的 Save 方法。 使用ITransaction管理事務 在 NHibernate 中,事務通過 ITransaction 介面進行管理,這確保了數據的完整性和一致性。 使用來自 ISession 的 BeginTransaction 方法,開發人員可以確保所有操作都成功完成後再提交資料到資料庫,或在出現問題時回滾,從而保持數據的穩定性。 完整的代碼示例 這個示例包括 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,而不需要重寫你的資料訪問層。 為各種資料庫系統(如 SQL 伺服器)調整 NHibernate NHibernate 中的 XML 配置文件允許開發人員指定各自資料庫系統的 SQL 方言。 這使 NHibernate 成為一個靈活的解決方案,可以輕鬆適應幾乎所有支持 SQL 的關聯資料庫,確保您的應用程式在不同的資料庫系統中可移植。 在 NHibernate 中使用 IronPDF 將 NHibernate 與 IronPDF 整合是一個強大的組合,可以增強您的 .NET 應用程式。 它允許您使用 NHibernate 管理資料庫操作,同時利用 IronPDF 從您的數據生成 PDF 文件。 考慮一種情況,您的應用程式需要提供特定於用戶的文件,例如何需生成和下載以 PDF 格式顯示的員工報告。 NHibernate 可以有效地管理從您的資料庫中檢索數據的過程,而 IronPDF 可以將這些數據轉換為格式良好的 PDF 文件。 首先,確保你的項目安裝了 IronPDF 庫。 首先,確保 IronPDF 被添加到你的項目中。 您可以通過安裝 IronPDF 封裝將其納入到 NuGet 封裝管理器中。 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 $vbLabelText $csharpLabel 在此代碼中,OpenSession() 是一個初始化 NHibernate 會話的方法,用於獲取員工數據。 IronPDF 的 ChromePdfRenderer 類將填充了獲取數據的 HTML 模板渲染為 PDF。 此 PDF 被本地保存,也可以通過網路介面直接傳送給用戶。 結論 在本教程中,我們探索了 NHibernate 如何簡化 .NET 應用程式中的資料庫操作以及它與 IronPDF 的整合如何通過允許生成動態 PDF 文檔來增強功能。 NHibernate 提供強大的數據管理工具,而 IronPDF 提供了一種方便的方法,可以從用數據填充的 HTML 模板中創建專業質量的 PDF。 IronPDF is available for a free trial, and licenses begin at a cost-effective solution for integrating powerful PDF generation into your applications. 這些工具共同提供了一個完整的解決方案來管理數據和生成文件,非常適合於企業級和小規模專案。 常見問題解答 如何在 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 映射文件配置它,以定義數據庫設置和對象映射。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Ocelot .NET(對於開發者的運行原理)Rebus .NET Core 示例(對於開...