欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何在.NET Core应用中使用NHibernate详解

程序员文章站 2022-06-24 23:23:24
前言 nhibernate 来源于非常优秀的基于java的hibernate 关系型持久化工具。nhibernate 最近发布了 5.1.3 版本, 支持 .net st...

前言

nhibernate 来源于非常优秀的基于java的hibernate 关系型持久化工具。nhibernate 最近发布了 5.1.3 版本, 支持 .net standard 2.0 , 这意味着可以在 .net core 2.0 应用中使用, 本文就已 webapi 应用为例, 介绍一下如何在 .net core 应用中如何使用 nhibernate 。下面话不多说了,来一起看看详细的介绍的吧

使用方法如下:

1、 新建一个基于 .net core 的 web api应用, 命令如下:

mkir webapitest
cd webapitest/
dotnet new webapi

2、 添加 nhibernate 包以及对应的数据库驱动程序(以 npgsql 为例):

dotnet add pakcage nhibernate
dotnet add package nhibernate.netcore
dotnet add package npgsql

现在打开项目文件 webapitest.csproj , 可以看到已经添加了这些包:

 <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、 在项目中新建一个 models 目录, 并创建实体类以及对应的 xml 映射文件, 代码如下:

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; }
 }
}

对应的 xml 映射文件如下:

<?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>

这些都是 nhibernate 的常规做法, 因此不做过多介绍, 不熟悉的可以查阅 nhibernate 的相关文档。

4、 将 xml 文件编译为嵌入的资源, 打开项目文件 webapitest.csproj , 添加一个 itemgroup 节点:

<itemgroup>
 <none remove="models/*.hbm.xml" />
 <embeddedresource include="models/*.hbm.xml" />
</itemgroup>

5、 创建 nhibernate 的配置文件, 并设置为复制到输出目录:

<?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>

打开项目文件, 添加 itemgroup 节点, 内容如下:

<itemgroup>
 <content update="hibernate.config">
 <copytooutputdirectory>always</copytooutputdirectory>
 </content>
</itemgroup>

6、 修改 startup.cs 文件, 将 nhibernate 集成到 .net core 内置的依赖注入框架中:

6.1、 修改 startup.cs 的 using 部分, 添加下面的语句:

using microsoft.extensions.logging;
using nhibernate.netcore;

6.2、 修改 startup.cs 的构造函数, 代码如下:

public startup(
 iconfiguration configuration,
 iloggerfactory factory
) {
 configuration = configuration;
 // 将内置的日志组件设置为 nhibernate 的日志组件
 factory.useashibernateloggerfactory();
}

6.3、 修改 configureservices 方法, 添加 nhibernate 相关的服务:

public void configureservices(iservicecollection services) {
 // nhibernate 配置文件的路径
 var path = system.io.path.combine(
  appdomain.currentdomain.basedirectory,
  "hibernate.config"
 );
 // 添加 nhibernate 相关的服务
 services.addhibernate(path);
 services.addmvc()
  .setcompatibilityversion(compatibilityversion.version_2_1);
}

7、 修改默认的 valuescontroller.cs , 注入并使用 nhibernate:

7.1、 修改构造函数, 注入 isessionfactory :

public valuescontroller(isessionfactory factory) {
 this.factory = factory;
}

7.2、 修改 get 方法, 使用 nhibernate 进行查询:

// get api/values
[httpget]
public actionresult<ienumerable<gpsposition>> get() {
 using (var session = factory.opensession()) {
  var query = session.query<gpsposition>();
  return query.tolist();
 }
}

8、 编译并运行:

dotnet run

之后可以看到类似这样的 nhibernate 初始化信息:

using launch settings from ~/projects/webapitest/properties/launchsettings.json...
info: nhibernate.cfg.environment[0]
  nhibernate 5.1.3 (assembly 5.1.0.0)
info: nhibernate.cfg.environment[0]
  hibernate-configuration section not found in application configuration file
info: nhibernate.cfg.environment[0]
  bytecode provider name : lcg
info: nhibernate.cfg.environment[0]
  using reflection optimizer
dbug: nhibernate.cfg.configuration[0]
......
hosting environment: development
content root path: ~/projects/webapitest
now listening on: https://localhost:5001
now listening on: http://localhost:5000
application started. press ctrl+c to shut down.

看到这些信息, 就表示已经可以正常的使用 nhibernate 了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。