Nhibernate入门与demo 升级版

       在第一篇文章中有几个地方作为第一个Nhibernate入门demo还有很多不足!今天特意写点补充知识!请先阅读:Nhibernate入门与demo

以下是我们项目的升级的地方:

先看一下程序结构的截图:

问题一:关于hibernate.cfg.xml配置文件。

文件名称必须是hibernate.cfg.xml 。Nhibernate自动到项目输出中查找此文件。必须将此文件的属性设置为始终复制。

问题二:在webconfig中配置Nhibernate,不使用单独的:hibernate.cfg.xml

在webconfig中配置Nhibernate是我们另外一种配置方式。格式如下:

代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Add this element -->
<configSections>
<section
name="hibernate-configuration"
type
="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
/>
</configSections>

<!-- Add this element -->
<hibernate-configuration xmlns="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);initial catalog=hkTemp;Integrated Security=SSPI
</property>
<mapping assembly="NhibernateDemo" />
</session-factory>
</hibernate-configuration>

<!-- Leave the system.web section unchanged -->
<system.web>
...
</system.web>
</configuration>

解释:NHibernate通过方言(dialect)区分 我们配置的是使用 Microsoft SQL Server 2005数据库并且通过指定的连接字符串连接数据库

问题三:sessionFactory 是针对一个数据库,所以我们可以采用单例模式来实现一个NhibernateHelper。看下面代码【这是官方给的NhibernateHelper实现】

代码
public sealed class NhibernateHelper
{
private const string CurrentSessionKey = "nhibernate.currentsession";
private static readonly ISessionFactory sessionFactory;

static NhibernateHelper()
{
Configuration cfg
= new Configuration();

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

上面NhibernateHelper不报错的基础是:你在webconfig中正确配置Nhibernate或者添加了hibernate.cfg.xml配置文件。【注意文件名必须是这个】

这样实现后我们的调用代码就变得简单多了,看一下代码

 

ISession session = NhibernateHelper.GetCurrentSession();
//.....User 初始化
session.Save(User);
session.Delete(User);
session.Update(User);

 

 

以上是简单的这个demo的一个小小的升级!

 

源码下载:NhibernateDemo-2.0.zip

posted @ 2010-09-18 12:45  FlyDragon  阅读(3686)  评论(13编辑  收藏  举报