看了一些别人写的关于Nhibernate如何使用的文章,并按照例子写了一些简单的程序,发现总有一些注意不到的地方而使程序不能运行,在修改的过程中也有一些认识,所以就用文字记录下来,以备将来作个参考。
Nhibernate作为OR映射工具在一定程度上简化了对数据库的操作,它的使用过程实际上分为两个部分,一是获得一个SessionFactory,另一部分就是通过SessionFactory得到Session,然后通过Session进行对象数据库操作。下面详细介绍这两个过程,SessionFactory针对一个数据库连接,如果在一个程序中要用到多个数据库,则要创建多个SessionFactory。SessionFactory是由Configuration创建的,创建它的方法是Configuration.buildSessionFactory()。创建一个什么样的SessionFactory(也即操作什么样的数据库以及操作数据库的哪些表)是由Configure来决定的。生成Configure以及对其配置有多种方法,主要有以下几种,我们通常使用一个工具类NHibernateHelper来提供SessionFactory,NHibernateHelper维护唯一个静态SessionFactory实例,该类结构如下
using System;
using System.Text;
using System.Collections;
using System.Data;
using NHibernate.Cfg;
using NHibernate;
using NHibernate.Engine;
namespace NhibernateHelper
{
/// <summary>
///
/// </summary>
public class NHibernateHelper
{
private static NHibernate.ISessionFactory SessionFactory = null;
public NHibernateHelper()
{
// TODO: 在此处添加构造函数逻辑
}
private static ISessionFactory GetSessionFactory(string assemblyName)
{
if (SessionFactory != null)
{
return SessionFactory;
}
Else
{
通过Configure生成一个SessionFactory
}
}
private static ISessionFactory GetSessionFactory()
{
return GetSessionFactory(null);
}
public static ISession CurrentSession()
{
ISessionFactory factory = GetSessionFactory();
try
{
ISession Session = factory.OpenSession();
return Session;
}
catch (Exception e)
{
NHibernate.HibernateException ex = new HibernateException(e);
throw (ex);
}
}
public static void ReloadConfig()
{
SessionFactory = null;
}
}
}
下面要讲讲生成Configure的方法了
1、 通过读取App.config配置Configure
App.config示例如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<!--oracle-->
<property name="dialect">NHibernate.Dialect.OracleDialect</property>
<propertyname="connection.provider">NHibernate.Connection.DriverConnectionProvider
</property>
<property name="connection.driver_class">NHibernate.Driver.OracleClientDriver
</property>
<property name="connection.connection_string">Data Source=nacstest;user id=apps;password=apps</property>
<property name="show_sql">true</property>
<!--ms sql
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">Server=localhost;initial catalog=Test;Integrated Security=SSPI;</property>
<property name="max_fetch_depth">3</property>
<property name="show_sql">true</property>-->
<!--other-->
</session-factory>
</hibernate-configuration>
</configuration>
对hibernate的有关数据库的app.config信息配置好后,下面就是生成Configuration了
Configuration configure= new Configuration();
Configure. Configure();//这里默认是读取App.config文件