C#Data Operations Series - 10 NHibernate Trial

Keywords: C# Session Hibernate Database SQL

0. Preface

In the last article, you basically completed the introductory tutorial for EF Core.Starting with this article, we'll try to explore more ORM frameworks on the.net core platform.So let's start with NHibernate.

1. Introduction to NHibernate

NHibernate is the C#version of Hibernate, known as the pillar of ORM in Java (at least once).Hibernate can be said to have opened up the world of Java, when the SSH Trolley was popular all over the world, Hibernate has played an important role so far.

However, unlike the EntityFramework, Hibernate relies on configuration files, which are used through configuration file specifications, and Object/Relation mappings.NHibernate inherits this and prefers configuration files.Here's how NHibernate works:

By reading App.config perhaps Web.config The file reads the basic configuration of NHibernate, then loads the mapping file to establish the mapping relationship.In subsequent use, SQL statements are generated from mapping relationships (this step is consistent with EF) to manipulate or query data.

2. Exploring NHibernate

2.1Get ready

I'll start with a console project, named dataprovider.Then install NHibernate:

  1. NuGet:
Install-Package NHibernate
  1. dotnet core command line:
dotnet add package NHibernate

The Hibernate version used in this article is5.2.7

2.2To configure

You need to create a configuration file for your project:App.config.

In C#projects, the name of the main profile for each project is App.config This is a fixed name.

The contents of the file are as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

Add the following between the configuration nodes:

<configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>

The meaning of this code is that a hibernate-configuration node is added to the config file, and the resolution of the node is done by the class:NHibernate.Cfg.Configuration SectionHandler, in which package is NHibernate.

stay App.config Add the following code to the file configuration node:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
        <property name="connection.connection_string">
            Data Source=.;Initial Catalog=Demo;Integrated Security=True
        </property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping assembly="dataprovider" />
    </session-factory>
</hibernate-configuration>

This is a fixed format, where dialect represents the type of database used.connection.connection_string represents a connection string.Mapping represents the project in which the mapping relationship file resides.

2.3Get ISessionFactory

Then get an ISessionFactory:

Configuration cfg = new Configuration();
var sessionFactory = cfg.BuildSessionFactory();

Of course, if you run the code directly, an error will be reported here in BuildSessionFactory.Because there is no data access driver installed for SQL Server:

System.Data.SqlClient

Once the data access driver installation is successful, run to get the sessionFactory.

Session Factory is used to create a Session to access the database

2.4crud

Let's start with a simple example class:

public class Cat
{
    public virtual string Id { get; set; }
    public virtual string Name { get; set; }
    public virtual char Sex { get; set; }
    public virtual float Weight { get; set; }
}

Mapping relationship file for NHibernate:Cat.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="dataprovider" assembly="dataprovider">
  <class name="Cat" table="Cat">

    <!-- A 32 hex character is our surrogate key. It's automatically
            generated by NHibernate with the UUID pattern. -->
    <id name="Id">
      <column name="CatId" sql-type="char(32)" not-null="true"/>
      <generator class="uuid.hex" />
    </id>
    <!-- A cat has to have a name, but it shouldn't be too long. -->
    <property name="Name">
      <column name="Name" length="16" not-null="true" />
    </property>
    <property name="Sex" />
    <property name="Weight" />
  </class>
</hibernate-mapping>

Once created, right-click the file and modify the file generation to a nested resource

Then write the sample code:

Configuration cfg = new Configuration().Configure();

using (var sessionFactory = cfg.BuildSessionFactory())
using (var session = sessionFactory.OpenSession())
{
// Operation through session
    session.Close();
}

Add a new Cat:

var princess = new Cat
{
    Name = "Princess",
    Sex = 'F',
    Weight = 7.4f
};
session.Save(princess);
session.Flush();//Push changes to the database, no data will be in the database if not called

Query and modify:

var cats = session.Query<Cat>().ToList();
var cat = cats.First();
cat.Name = "xiao li";
session.Update(cat);
session.Flush();

Query and delete:

var cats = session.Query<Cat>().ToList();
var cat = cats.First();
session.Delete(cat);
session.Flush();

This is an introductory tutorial for NHibernate.Well, here's a picture of NHibernate:

3. Summary

NHibernate continues Hibernate's strengths, and it's not difficult for anyone who's known Hibernate before.Lightweight and simple, but requires a configuration file.The next issue will lead you further into NHibernate.

Please pay attention to more content My blog, Mr. Gao's Cabin

Posted by Josh18657 on Tue, 19 May 2020 18:04:34 -0700