How to use NHibernate in. NET Core application

  • 2021-10-25 06:31:35
  • OfStack

Preface

Nhibernate comes from the excellent Hibernate relational persistence tool based on Java. NHibernate has recently released version 5.1. 3, which supports. NET Standard 2.0, which means that it can be used in. NET Core 2.0 applications. This article takes the WebAPI application as an example to introduce how to use NHibernate in. NET Core applications under 1. The following words are not much to say, let's take a look at the detailed introduction

The usage method is as follows:

1. Create a new Web API application based on. NET Core. The command is as follows:


mkir WebApiTest
cd WebApiTest/
dotnet new webapi

2. Add NHibernate package and corresponding database driver (take Npgsql as an example):


dotnet add pakcage NHibernate
dotnet add package NHibernate.NetCore
dotnet add package Npgsql

Now open the project file WebApiTest. csproj, and you can see that these packages have been added:


 <ItemGroup>
 <PackageReference Include="Microsoft.AspNetCore.App" />
 <PackageReference Include="NHibernate" Version="5.1.3" />
 <PackageReference Include="NHibernate.NetCore" Version="1.0.1" />
 <PackageReference Include="NpgSql" Version="4.0.2" />
 </ItemGroup>

3. Create a new Models directory in the project, and create entity classes and corresponding xml mapping files. The code is as follows:


namespace WebApiTest.Models {

 public class GpsPosition {
 public virtual long Id { get; set; }
 public virtual string UserAgent { get; set;}
 public virtual long? Timestamp { get; set; }
 public virtual float? Latitude { get; set; }
 public virtual float? Longitude { get; set; }
 public virtual float? Accuracy { get; set; }
 public virtual float? Altitude { get; set; }
 public virtual float? AltitudeAccuracy { get; set; }
 public virtual float? Heading { get; set; }
 public virtual float? Speed { get; set; }
 public virtual string Tag { get; set; }
 }
}

The corresponding xml mapping file is as follows:


<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns="urn:nhibernate-mapping-2.2"
 namespace="WebApiTest.Models"
 assembly="WebApiTest">
 <class name="GpsPosition" schema="public" table="gps_position">
 <id name="Id" column="id" type="long">
 <generator class="sequence">
 <param name="sequence">public.gps_position_id_seq</param>
 </generator>
 </id>
 <property name="UserAgent" column="user_agent" type="string" />
 <property name="Timestamp" column="timestamp" type="long" />
 <property name="Latitude" column="latitude" type="float" />
 <property name="Longitude" column="longitude" type="float" />
 <property name="Accuracy" column="accuracy" type="float" />
 <property name="Altitude" column="altitude" type="float" />
 <property name="AltitudeAccuracy" column="altitude_accuracy" type="float" />
 <property name="Heading" column="heading" type="float" />
 <property name="Speed" column="speed" type="float" />
 <property name="Tag" column="tag" type="string" />
 </class>
</hibernate-mapping>

These are the common practices of NHibernate, so we don't introduce them too much. If you are unfamiliar with them, you can refer to the relevant documents of NHIbernate.

4. Compile the xml file into an embedded resource, open the project file WebApiTest. csproj, and add an ItemGroup node:


<ItemGroup>
 <None Remove="Models/*.hbm.xml" />
 <EmbeddedResource Include="Models/*.hbm.xml" />
</ItemGroup>

5. Create the configuration file of NHibernate and set it to copy to the output directory:


<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
 <session-factory>
 <property name="connection.connection_string">server=localhost;database=test_db;user id=postgres;password=postgres;</property>
 <property name="dialect">NHibernate.Dialect.PostgreSQL83Dialect</property>
 <property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
 <property name="show_sql">true</property>
 <property name="format_sql">true</property>
 <property name="adonet.batch_size">10</property>
 <mapping assembly="NaturalReserveApi" />
 </session-factory>
</hibernate-configuration>

Open the project file and add the ItemGroup node as follows:


<ItemGroup>
 <Content Update="hibernate.config">
 <CopyToOutputDirectory>Always</CopyToOutputDirectory>
 </Content>
</ItemGroup>

6. Modify the Startup. cs file to integrate NHibernate into the built-in dependency injection framework of NET Core:

6.1. Modify the using section of Startup. cs to add the following statement:


using Microsoft.Extensions.Logging;
using NHibernate.NetCore;

6.2. Modify the constructor of Startup. cs as follows:


public Startup(
 IConfiguration configuration,
 ILoggerFactory factory
) {
 Configuration = configuration;
 //  Set the built-in logging component to  NHibernate  Log component of 
 factory.UseAsHibernateLoggerFactory();
}

6.3. Modify the ConfigureServices method to add NHibernate-related services:


dotnet add pakcage NHibernate
dotnet add package NHibernate.NetCore
dotnet add package Npgsql
0

7. Modify the default ValuesController. cs, inject and use NHibernate:

7.1. Modify the constructor and inject ISessionFactory:


dotnet add pakcage NHibernate
dotnet add package NHibernate.NetCore
dotnet add package Npgsql
1

7.2. Modify the Get method to query using NHibernate:


dotnet add pakcage NHibernate
dotnet add package NHibernate.NetCore
dotnet add package Npgsql
2

8. Compile and run:


dotnet run

You can then see NHibernate initialization information like this:


dotnet add pakcage NHibernate
dotnet add package NHibernate.NetCore
dotnet add package Npgsql
4

Seeing this information means that NHibernate can be used normally.

Summarize


Related articles: