nhibernate链接oracle

NHibernate是一款开源的ORM框架,现在被广泛应用于数据访问层的开发。NHibernate的功能丰富,它可以支持各种数据库,包括Oracle数据库。下面我们就来看看如何使用NHibernate链接Oracle数据库。

首先,我们需要在项目中引入NHibernate和Oracle.Data.dll的相关包。

<package id="NHibernate" version="5.2.3.0" targetFramework="net452" />
<package id="Oracle.ManagedDataAccess" version="12.1.24160419" targetFramework="net452" />

然后,我们需要在Web.config或App.config中配置数据库链接信息。

<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.OracleManagedDataClientDriver</property>
<property name="connection.connection_string">Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxx.xxx.xxx.xxx)(PORT=1521)))(CONNECT_DATA=(SID=xxxx)));User ID=xxxx;Password=xxxx;</property>
<property name="dialect">NHibernate.Dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
</session-factory>
</hibernate-configuration>

其中,connection_string需要修改成自己的实际信息。这里我们采用使用Oracle.ManagedDataAccess提供的OracleManagedDataClientDriver,其主要优势是支持.NET Framework和.NET Core平台,提供更高的性能和安全性。

接下来,我们需要定义实体和映射文件,在这里我们创建一个名为Student的实体类及其映射文件Student.hbm.xml。

//Student.cs
public class Student
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime BirthDate { get; set; }
}
//Student.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Student" table="Student">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="BirthDate" column="BirthDate" />
</class>
</hibernate-mapping>

最后,我们就可以使用NHibernate进行数据操作了。这里我们通过一个简单的示例来说明如何实现使用NHibernate链接Oracle数据库,并进行数据的增删查改操作。

using NHibernate;
using NHibernate.Cfg;
using System;
class Program
{
static void Main(string[] args)
{
Configuration cfg = new Configuration();
cfg.Configure();     
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
{
//数据插入
Student stu = new Student()
{
Name = "Tom",
BirthDate = new DateTime(1990, 5, 5)
};
session.Save(stu);
//数据查询
var list = session.CreateCriteria(typeof(Student)).List();
foreach (var item in list)
{
Console.WriteLine($"ID:{item.Id},Name:{item.Name},BirthDate:{item.BirthDate}");
}
//数据更新
Student stu2 = new Student()
{
Id = 1,
Name = "Tom2",
BirthDate = new DateTime(1992, 5, 5)
};
session.Update(stu2);
//数据删除
var stu3 = session.Get<Student>(1);
session.Delete(stu3);
session.Flush();
}
Console.ReadLine();
}
}

NHibernate使用简单,且易于扩展和维护。我们可以通过学习NHibernate的使用,快速地完成对Oracle数据库的访问。当然,缺点也是显而易见的,如使用NHibernate进行数据操作,性能会有所下降,需要更多的系统资源才能达到和手写SQL相同的性能表现。

本文链接:https://my.lmcjl.com/post/12260.html

展开阅读全文

4 评论

留下您的评论.