一、Nhibernate是什么?
要想理解Nhibernate,首先要明白什么是ORM。ORM--对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。通俗讲,就是我们操作实体类,然后让ORM框架自动映射到数据库中。Nhibernate就是:.Net环境下实现ORM的技术的一个框架!
二、Nhibernate能做什么?
使用Nhibernate前,我们数据操作主要用在D层,将数据的插入直接拼成sql字符串,然后去操作数据库。如下:
INSERT INTO table_name(列1, 列2,...) VALUES (值1, 值2,....)
SELECT * FROMtable_name
UPDATE Person SETFirstName = 'Fred' WHERE LastName = 'Wilson'
DELETE FROM table_nameWHERE 列名称 = 值
使用Nhibernate后:
Entity my Entity =newEntity();//Entity初始化........
session.Save(myEntity );//保存一个用户
session.Update(myEntity );//更新用户
session.Delete(myEntity );//删除用户
Entityuser =session.Get<Entity>(Id) as Entity;//根据主键获取用户的 用户实例
注:这里的Entity,代指所有不同的实体,想保存哪个实体写具体的实体就可以了。
当对数据进行再次操作的时候,只需用session将初始化好的实体进行增删查改就OK了。
三、怎么搭建一个Nhibernate程序
下图是建立一个使用基础的Nhibernate的Demo,所有文件如图示:
创建过程如下:
第一步:创建dog实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class Dog
{
private string id;
private string name;
private string sex;
private string weight;
public Dog()
{
}
public virtual string Id
{
get { return id; }
set { id = value; }
}
public virtual string Name
{
get { return name; }
set { name = value; }
}
public virtual string Sex
{
get { return sex; }
set { sex = value; }
}
public virtual string Weight
{
get { return weight; }
set { weight = value; }
}
}
}
第二步:创建Dog类的映射文件 命名规则:xxx.hbm.xml ,我们写作Dog.hbm.xml 代码如下:
<?xmlversion="1.0" encoding="utf-8" ?>
<hibernate-mappingxmlns="urn:nhibernate-mapping-2.2" namespace="Model"assembly="Model">
<class name="Dog"table="Dog">
<id name="Id">
<column name="DogId"sql-type="char(32)" />
<generator class="assigned"/>
</id>
<property name="Name">
<column name="Name"length="16" />
</property>
<property name="Sex" />
<property name="Weight" />
</class>
</hibernate-mapping>
注意该文件的属性设置如下
第三步:创建Nhibernate的配置文件:hibernate.cfg.xml 代码如下:
<?xmlversion="1.0" encoding="utf-8" ?>
<hibernate-configurationxmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">
Server=(local);uid=sa;pwd=123456;database=quickstart //将该属性的填写改成你自己的数据库连接符
</property>
<property name="hbm2ddl.auto">update</property>
<mapping assembly="Model"/>
</session-factory>
</hibernate-configuration>
第四步:使用和测试
我们在web层引入两个dll文件,NHibernate.ByteCode.LinFu、NHibernate,
引入以下命名空间:
using NHibernate;
using NHibernate.Cfg;
执行以下代码:
ISession session =NHibernateHelper.GetCurrentSession();
ITransaction tx =session.BeginTransaction();
Dog prince = new Dog();
prince.Id = "DogId";
prince.Name = "prince";
prince.Sex = "男";
prince.Weight = "60";
session.Save(prince);
tx.Commit();
NHibernateHelper.CloseSession();
这里为了保证程序里只用一个session,还加了一个 NHibernateHelper,其代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using System.Web.UI;
namespace QuickStart
{
public sealed class NHibernateHelper
{
private const string CurrentSessionKey= "nhibernate.current_session";
private static readonly ISessionFactorysessionFactory;
static NHibernateHelper()
{
sessionFactory = newConfiguration().Configure().BuildSessionFactory();
}
public static ISessionGetCurrentSession()
{
HttpContext context =HttpContext.Current;
ISession currentSession =context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession =sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
HttpContext context =HttpContext.Current;
ISession currentSession =context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static voidCloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
看数据库里是不是已经有了一张Dog表,而且一条数据已经插入到了表中,真得so easy!
本文介绍了Nhibernate——一种.NET环境下的ORM框架,并详细展示了如何通过Nhibernate进行数据操作,包括实体类定义、映射文件配置及基本的CRUD操作。
1341





