nhibernate处理多数据库

When using NHibernate in an ASP.NET application it is important to manage sessions correctly. Typically, a session-per-request pattern is used with a single session created and used for the lifetime of a request and then discarded. This helper project makes using NHibernate with ASP.NET easier by automating the creation of sessions and ensuring that they are closed after each request. It also provides some convenient methods to make coding simpler and more readable:

Automatically create the database schema:

Db.CreateDatabase();
Load an object from the database

Customer customer = (Customer)Db.Load(typeof(Customer), 123);
Save an object:

Db.Save(Customer);
Delete an object:

Db.Delete(Customer);
Access to the NHibernate Configuration and SessionFactory objects are provided if needed.

Configuration
NHibernate already has a comprehensive and flexible configuration system where settings can be defined in code, in the web.config file or in a separate XML file. Using the separate XML file enables the location of the mapping files to be configured as required. The configuration below defines the NHibernate connection properties and driver classes to use (these could also be defined in the web.config file) and the location of the nhibernate mapping files (in this case the assembly 'MyAssembly' which would contain embedded resources).

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.0" >
<session-factory name="chat">
<!-- properties -->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI</property>
<property name="show_sql">false</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="use_outer_join">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<!-- mapping files -->
<mapping assembly="MyAssembly" />
</session-factory>
</hibernate-configuration>

Rather than simply use the default filename "nhibernate.cfg.xml" I prefer instead to use "nhibernate.config", mainly because using an xml file extension is a security risk as the config file could easily be downloaded whereas access to the .config extension is restricted by ASP.NET automatically. To provide some extra flexibility the name of the file is specified in the <appSetting> section with the key "nhibernate.config":

<appSettings>
<add key="nhibernate.config" value="~/nhibernate.config" />
</appSettings>

Now, the only other thing that needs to be added to the web.config file is the entry for the HttpModule:

<httpModules>
<add name="NHibernateModule" type="NHibernate.Helper.Module, NHibernate.Helper" />
</httpModules>

Here is the HttpModule itself. As you can see, it is extremly simple and simply closes the connection at the end of the request.

using System;
using System.Web;
namespace NHibernate.Helper
{
/// <summary>
///        HttpModule to automatically close a session at the end of a request
/// </summary>
public sealed class Module : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(EndRequest);
}
public void Dispose() { }
public void EndRequest(Object sender, EventArgs e)
{
Db.CloseSession();
}
}
}

The Db class contains all the helper methods and manages the creation and lifetime of the sessions (with the HttpModule above).

using System;
using System.Web;
using System.Configuration;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernate.Helper
{
/// <summary>
///        Provides access to a single NHibernate session on a per request basis.
/// </summary>
/// <remarks>
///        NHibernate requires mapping files to be loaded. These can be stored as
///        embedded resources in the assemblies alongside the classes that they are for or
///        in separate XML files.
///        <br /><br />
///        As the number of assemblies containing mapping resources may change and
///        these have to be referenced by the NHibernate config before the SessionFactory
///        is created, the configuration is stored in a separate config file to allow
///        new references to be added. This would also enable the use of external mapping
///        files if required.
///        <br /><br />
///        The name of the NHibernate configuration file is set in the appSettings section
///        with the name "nhibernate.config". If not specified the the default value of
///        ~/nhibernate.config is used.
///        <br /><br />
///        Note that the default config name is not used because the .xml extension is
///        public and could be downloaded from a website whereas access to .config files is
///        automatically restricted by ASP.NET.
/// </remarks>
public sealed class Db
{
/// <summary>
/// Key used to identify NHibernate session in context items collection
/// </summary>
private const string sessionKey = "NHibernate.Db";
/// <summary>
/// NHibernate Configuration
/// </summary>
private static readonly Configuration configuration = new Configuration();
/// <summary>
/// NHibernate SessionFactory
/// </summary>
private static readonly ISessionFactory sessionFactory = configuration.Configure( HttpContext.Current.Request.MapPath(ConfigurationSettings.AppSettings["nhibernate.config"]) ).BuildSessionFactory();
/// <summary>
/// NHibernate Session. This is only used for NUnit testing (ie. when HttpContext
/// is not available.
/// </summary>
private static readonly ISession session = sessionFactory.OpenSession();
/// <summary>
/// None public constructor. Prevent direct creation of this object.
/// </summary>
private Db() { }
/// <summary>
/// See beforefieldinit
/// </summary>
static Db() { }
/// <summary>
/// Creates a new NHibernate Session object if one does not already exist.
/// When running in the context of a web application the session object is
/// stored in HttpContext items and has 'per request' lifetime. For client apps
/// and testing with NUnit a normal singleton is used.
/// </summary>
/// <returns>NHibernate Session object.</returns>
[CLSCompliant(false)]
public static ISession Session
{
get
{
ISession session;
if (HttpContext.Current == null)
{
session = Db.session;
}
else
{
if (HttpContext.Current.Items.Contains(sessionKey))
{
session = (ISession)HttpContext.Current.Items[sessionKey];
}
else
{
session = Db.sessionFactory.OpenSession();
HttpContext.Current.Items[sessionKey] = session;
}
}
return session;
}
}
/// <summary>
/// Closes any open NHibernate session if one has been used in this request.<br />
/// This is called from the EndRequest event.
/// </summary>
[CLSCompliant(false)]
public static void CloseSession()
{
if (HttpContext.Current == null)
{
Db.session.Close();
}
else
{
if (HttpContext.Current.Items.Contains(sessionKey))
{
ISession session = (ISession)HttpContext.Current.Items[sessionKey];
session.Close();
HttpContext.Current.Items.Remove(sessionKey);
}
}
}
/// <summary>
/// Returns the NHibernate Configuration object.
/// </summary>
/// <returns>NHibernate Configuration object.</returns>
[CLSCompliant(false)]
public static Configuration Configuration
{
get { return Db.configuration; }
}
/// <summary>
/// Returns the NHibernate SessionFactory object.
/// </summary>
/// <returns>NHibernate SessionFactory object.</returns>
[CLSCompliant(false)]
public static ISessionFactory SessionFactory
{
get { return Db.sessionFactory; }
}
/// <summary>
/// Loads the specified object.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="id">Id.</param>
public static void Load(System.Type type, object id)
{
Db.Session.Load(type, id);
}
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="id">Id.</param>
public static object Get(System.Type type, object id)
{
return Db.Session.Get(type, id);
}
/// <summary>
/// Save object item using NHibernate.
/// </summary>
/// <param name="item">Object to save</param>
public static void Save(object item)
{
ITransaction transaction = Db.Session.BeginTransaction();
try
{
Db.Session.Save(item);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Save object item using NHibernate.
/// </summary>
/// <param name="item">Object to delete</param>
public static void Delete(object item)
{
ITransaction transaction = Db.Session.BeginTransaction();
try
{
Db.Session.Delete(item);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Creates the specified database.
/// </summary>
/// <param name="script">Script.</param>
/// <param name="export">Export.</param>
public static void CreateDatabase()
{
NHibernate.Tool.hbm2ddl.SchemaExport se = new NHibernate.Tool.hbm2ddl.SchemaExport(Db.Configuration);
se.Create(true, true);
}
}
}

nhibernate处理多数据库相关推荐

  1. nhibernate连接11g数据库

    我框架的数据映射用 nhibernate连接多数据库,这次又增加了oracle11g,负责开发的同事始终连接不上,悲催的sharepoint调试是在不方便... 下面描述下问题的解决,细节问题有3个: ...

  2. nhibernate 配置mysql_利用NHibernate与MySQL数据库交互

    本文章使用Visual Studio作为开发工具,并建立在已经安装MySQL数据库的前提. NHibernate是一个面向.NET环境的对象/关系数据库映射工具.官网:http://nhibernat ...

  3. 通过NHibernate ORM和CodeDom在任何数据库中自动生成表以生成代码

    目录 介绍 NHibernate NHibernate的优点: NHibernate缺点: NHibernate如何运作? CodeDOM CodeDOM的优点: CodeDOM缺点: 逐步使用代码 ...

  4. nhibernate mysql配置_NHibernate 连接多数据库怎么配置?

    NHibernate 连接多数据库怎么配置?是不是连一个数据库,就创建一个NHibernate.cfg.xml 或 配置文件?如果要连接6个数据库,就要创建6个配置文件,太麻烦了吧!有没有简单的写法? ...

  5. [NHibernate]基本配置与测试

    目录 写在前面 nhibernate文档 搭建项目 映射文件 持久化类 辅助类 数据库设计与连接配置 测试 总结 写在前面 一年前刚来这家公司,发现项目中使用的ORM是Nhibernate,这个之前确 ...

  6. NHibernate之Generator主键生成方式

    (1) assigned 主键由外部程序负责生成,无需NHibernate参与. (2) hilo 通过hi/lo 算法实现的主键生成机制,需要额外的数据库表保存主 键生成 历史状态. (3) seq ...

  7. 【转】NHibernate入门教程

    开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo 摘要: 热衷于开源框架探索的我发现A ...

  8. 开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo项目分析

    开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo,这个是一个在网上流传比较多的Spri ...

  9. NHibernate介绍

    在今日的企业环境中,把面向对象的软件和关系数据库一起使用可能是相当麻烦和浪费时间的.NHibernate是一个面向.NET环境的对象/关系数据库映射工具.对象/关系数据库映射(object/relat ...

最新文章

  1. WINRAR 命令行语法
  2. ubuntu 新建一个root用户
  3. select中option改变时跳转到其他页面
  4. linux宝塔面板配置可道云,使用宝塔面板配合可道云打造私有云
  5. 【pmcaff专栏】项目管理失败?如何避免?
  6. 自动控制matlab实验,自动控制matlab实验.doc
  7. Linux编程 3 (初识bash shell与man查看手册)
  8. 如何让组织的KPI成为敏捷转型的推手而不是杀手 | IDCF
  9. C# WPF 表单更改提示
  10. C语言 #include <> 与 #include “” 区别 - C语言零基础入门教程
  11. Android 在popupWindow上用autoCompleteTextView报错(Android 6.0报错,8.0没有问题)
  12. 随想录(一种新的读写锁的写法)
  13. CentOS7防火墙管理firewalld
  14. torch报告_Stack Overflow 2020调查报告发布,Rust 5连冠
  15. 谈谈Http中Get和Post的区别
  16. [Joy]冷笑话急转弯
  17. 无线信道的选择性衰落
  18. CrackMe160 学习笔记 之 023
  19. 刺激战场 枪支性能雷达图分析
  20. go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案

热门文章

  1. sql分类及基本sql操作,校对规则(mysql学习笔记二)
  2. 在Ubuntu Server 12.04 LTS上搭建可远程访问的Postgresql 9.1环境
  3. 利用 squid 反向代理提高网站性能
  4. hdu -4284 Travel(状态压缩)
  5. JSP简单练习-包装类综合应用实例
  6. NYOJ 228 士兵杀敌(五)
  7. docker学习(一)ubuntu上安装docker
  8. 第07课:【实战】调试Redis准备工作
  9. Mysql InnoDB 数据更新/删除导致锁表
  10. 三层架构与四大天王之——查