跳至页脚内容
.NET 帮助

NHibernate C#(开发人员如何使用)

NHibernate C#(开发人员的工作方式):图 1 - NHibernate C# 的主页

NHibernate 是一个专为 .NET 框架设计的强大的对象关系映射 (ORM) 框架。 它为开发人员提供了一种有效的方法来弥合 .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(Hibernate Query Language)查询数据库。

在 NHibernate 中将实体映射到数据库表

NHibernate 中的实体映射是通过通常用 XML 编写的映射文件来完成的。 这些文件通常以实体类命名(例如,Employee.hbm.xml),定义实体属性如何映射到数据库表的列。 一个典型的映射文件包括类名、表名以及关于每个属性的详细信息,包括主键、列名和数据类型。

详细了解映射文件中使用的属性和属性

在这些映射文件中,您可以为每个属性指定各种属性,例如非空约束或唯一性约束。 NHibernate 还允许进行复杂的映射,如一对多和多对一关系,提供了一整套强大的工具来在面向对象框架中表示关系型数据结构。

在 NHibernate 中执行 SQL 命令和事务

NHibernate 通过抽象底层的 SQL 命令来简化 CRUD(创建、读取、更新、删除)操作。 开发人员可以在不编写显式 SQL 代码的情况下执行这些操作,而是使用 ISession 接口提供的方法。 例如,要向数据库添加新实体,您只需创建对象的新实例,设置其属性,并使用 ISessionSave 方法。

使用 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 Server 切换到 MySQL 或 Oracle,而无需重写您的数据访问层。

适配各种数据库系统如 SQL Server 的 NHibernate

NHibernate 中的 XML 配置文件允许开发人员指定其数据库系统特定的 SQL 方言。 这使得 NHibernate 成为一个灵活的解决方案,可以轻松适应任何支持 SQL 的关系数据库,确保您的应用程序在不同的数据库系统中具有可移植性。

在 IronPDF 中使用 NHibernate

NHibernate C#(开发人员的工作方式):图 3 - IronPDF 的主页

将 NHibernate 与 IronPDF 集成是一种强大的组合,可以增强您的 .NET 应用程序。 它允许您通过 NHibernate 管理数据库操作,同时利用 IronPDF 从您的数据中生成 PDF 文档。 考虑一个场景,您的应用程序需要提供特定用户的文档,例如员工报告,这些文档需要生成并以 PDF 格式下载。 NHibernate 可以高效地管理从数据库中检索数据的过程,而 IronPDF 可以将这些数据转换为格式良好的 PDF 文件。

安装IronPDF

首先,确保将 IronPDF 添加到项目中。 您可以通过安装 IronPDF 包在 NuGet 包管理器中包含它。

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 被保存为本地文件,但也可以通过 Web 界面直接流式传输给用户。

结论

NHibernate C#(开发人员的工作方式):图 6 - IronPDF 许可页面

在本教程中,我们探讨了 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 可以通过使用 NHibernate 处理数据库操作和检索数据,然后由 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 映射文件来配置它,以定义数据库设置和对象映射。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。