NHibernate初步使用
1.创建一个网站项目:QuickStart
2.引用程序集:NHibernate.dll
3.更改配置文件加入以下节点:
<configSections>
<section
name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="QuickStart">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=.;initial catalog=Quickstart;Integrated Security=True</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<mapping assembly="QuickStart"/>
</session-factory>
</hibernate-configuration>
4.创建模型类:
namespace QuickStart.Models
{
public class Cat
{
private string id;
private string name;
private char sex;
private float weight; public Cat()
{
} public virtual string Id
{
get { return id; }
set { id = value; }
} public virtual string Name
{
get { return name; }
set { name = value; }
} public virtual char Sex
{
get { return sex; }
set { sex = value; }
} public virtual float Weight
{
get { return weight; }
set { weight = value; }
}
}
}
在这里注意我的命名空间为:
QuickStart.Models
5.映射模型类,加入一个xml文件,注意需要在vs里右键设置属性为:嵌入的资源

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="QuickStart.Models" //注意这里的namespace为模型类的命名空间--QuickStart.Models assembly="QuickStart">
<class name="Cat" table="Cat"> <!-- A 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' be too long. -->
<property name="Name">
<column name="Name" length="" not-null="true" />
</property>
<property name="Sex" />
<property name="Weight" />
</class> </hibernate-mapping>
这里需要注意指定namespace为模型类所在的命名空间.
6.在数据库中创建一样结构的数据表.
CREATE TABLE [dbo].[Cat](
[CatId] [char]() NOT NULL,
[Name] [nvarchar]() NOT NULL,
[Sex] [nchar]() NULL,
[Weight] [real] NULL,
CONSTRAINT [PK_Cat] PRIMARY KEY CLUSTERED
(
[CatId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
7.之后的操作就简单了,先创建一个NHibernateHelper.cs的类:
using System.Web;
using NHibernate;
using NHibernate.Cfg; namespace QuickStart.Helper
{
public sealed class NHibernateHelper
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory; static NHibernateHelper()
{
sessionFactory = new Configuration().Configure().BuildSessionFactory();
} public static ISession GetCurrentSession()
{
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 void CloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
8.开始操作,自己随便创建一个控制器验证代码是否可以顺利运行:
public class HomeController : Controller
{
//
// GET: /Home/ public string Index()
{
ISession session = NHibernateHelper.GetCurrentSession(); NHibernate.ITransaction tx = session.BeginTransaction(); Cat princess = new Cat();
princess.Name = "Princess";
princess.Sex = 'F';
princess.Weight = 7.4f; session.Save(princess);
tx.Commit(); NHibernateHelper.CloseSession();
return "";
} public string Query()
{
ISession session = NHibernateHelper.GetCurrentSession();
NHibernate.ITransaction tx = session.BeginTransaction(); IQuery query = session.CreateQuery("select c from Cat as c where c.Sex = :sex");
query.SetCharacter("sex", 'F');
foreach (Cat cat in query.Enumerable())
{
Response.Write("Name="+cat.Name);
} tx.Commit();
return "";
} }
9.结果如下:

10.项目结构如下:

NHibernate初步使用的更多相关文章
- 01-08-01【Nhibernate (版本3.3.1.4000) 出入江湖】NHibernate中的三种状态
以下属于不明来源资料: 引入 在程序运行过程中使用对象的方式对数据库进行操作,这必然会产生一系列的持久化类的实例对象.这些对象可能是刚刚创建并准备存储的,也可能是从数据库中查询的,为了区分这些对象,根 ...
- [转]NHibernate之旅(12):初探延迟加载机制
本节内容 引入 延迟加载 实例分析 1.一对多关系实例 2.多对多关系实例 结语 引入 通过前面文章的分析,我们知道了如何使用NHibernate,比如CRUD操作.事务.一对多.多对多映射等问题,这 ...
- [转]NHibernate之旅(9):探索父子关系(一对多关系)
本节内容 引入 NHibernate中的集合类型 建立父子关系 父子关联映射 结语 引入 通过前几篇文章的介绍,基本上了解了NHibernate,但是在NHibernate中映射关系是NHiberna ...
- [转]NHibernate之旅(3):探索查询之NHibernate查询语言(HQL)
本节内容 NHibernate中的查询方法 NHibernate查询语言(HQL) 1.from子句 2.select子句 3.where子句 4.order by子句 5.group by子句 实例 ...
- 集成 NHibernate
ABP 基础设施层——集成 NHibernate 本文翻译自ABP的官方教程<NHibernate Integration>,地址为:http://aspnetboilerplate.co ...
- 基于NHibernate二级缓存的MongoDB组件
设计一套基于NHibernate二级缓存的MongoDB组件(上) 摘要:NHibernate Contrib 支持很多第三方的二级缓存,如SysCache,MemCache,Prevalence ...
- NHibernate教程(20)——二级缓存(上)
本节内容 引入 介绍NHibernate二级缓存 NHibernate二级缓存提供程序 实现NHibernate二级缓存 结语 引入 上一篇我介绍了NHibernate内置的一级缓存即ISession ...
- NHibernate教程(19) —— 一级缓存
本节内容 引入 NHibernate一级缓存介绍 NHibernate一级缓存管理 结语 引入 大家看看上一篇了吗?对象状态.这很容易延伸到NHibernate的缓存.在项目中我们灵活的使用NHibe ...
- NHibernate教程(18)--对象状态
本节内容 引入 对象状态 对象状态转换 结语 引入 在程序运行过程中使用对象的方式对数据库进行操作,这必然会产生一系列的持久化类的实例对象.这些对象可能是刚刚创建并准备存储的,也可能是从数据库中查询的 ...
随机推荐
- ArrayList构造函数
//1.摘要: //初始化 System.Collections.ArrayList 类的新实例,该实例为空并且具有默认初始容量. // public ArrayList(); ArrayList a ...
- redis配置文件redis.conf的参数说明
打开redis.conf文件: # By default Redis does not run as a daemon. Use 'yes' if you need it. # Note that R ...
- CodeForces 685B Kay and Snowflake
树的重心,树形$dp$. 记录以$x$为$root$的子树的节点个数为$sz[x]$,重儿子为$son[x]$,重心为$ans[x]$. 首先要知道一个结论:以$x$为$root$的子树的重心$ans ...
- html基础及心得
html开始 <adress></adress>斜体(地址) <em><em>斜体(表示强调) <code></code>插入一 ...
- CentOS 6.5安装PostgreSQL9.3.5时报错: jade: Command not found
CentOS 6.5安装PostgreSQL9.3.5时报错: jade: Command not found 1[root@pghost1 postgresql-9.3.5]# ./configur ...
- android移动开发学习笔记(二)神奇的Web API
本次分两个大方向去讲解Web Api,1.如何实现Web Api?2.如何Android端如何调用Web Api?对于Web Api是什么?有什么优缺点?为什么用WebApi而不用Webservice ...
- linode更换Linux内核教程(独家)
Linode服务器性价比高,最低套餐2G内存,享受每月2TB流量,机房40Gb带宽,每月供需10美元(Linode优惠链接).Linode用户创建vps服务器后,可在后台自定义Linux系统版本,包括 ...
- Json字符串转Json对象
public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, Event ...
- web端和手机端测试有什么不同
面试中经常被问到web端测试和手机端测试有什么相同点和区别呢?现在总结一下这个问题,如有不对敬请指正 web端和手机端测试有什么区别 1.相同点 不管是web测试还是手机App测试,都离不开测试的相关 ...
- spring security:ajax请求的session超时处理
当前端在用ajax请求时,如果没有设置session超时时间并且做跳转到登录界面的处理,那么只是靠后台是很难完成超时的一系列动作的:但是如果后台 没有封装一个ajax请求公共类,那么在ajax请求上下 ...