NHibernateを利用しやすくなるヘルパークラスの実装 - NHibernateHelper例
2009/11/25 16:00Update
NHibernateを利用する際に、まずセッションを取得して、セッションからデータの取得やクエリの実行などの操作を行います。このNHibernateHelperクラスは、NHibernateを利用しやすくなるヘルパークラス実装の一例です。
NHibernateHelper 例
NHibernateHelper.cs/////////////////////////////////////////
// http://www.syboos.jp/nhibernate/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernate.Utils
{
/// <summary>
/// NHibernateのヘルパー(Helper)クラス
/// </summary>
public sealed class NHibernateHelper
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;
static NHibernateHelper()
{
sessionFactory = new Configuration().Configure("conf/nhibernate/hibernate.cfg.xml").BuildSessionFactory();
//sessionFactory = new Configuration().Configure("conf/nhibernate/hibernate.cfg.xml").AddClass(typeof(MyTable)).BuildSessionFactory();
}
/// <summary>
/// カレント・セッション取得
/// </summary>
/// <returns>セッションオブジェクト</returns>
public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = null;
if (context != null)
{
currentSession = context.Items[CurrentSessionKey] as ISession;
}
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
if (context != null)
{
context.Items[CurrentSessionKey] = currentSession;
}
}
return currentSession;
}
/// <summary>
/// カレント・セッションをクローズ
/// </summary>
public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = null;
if (context != null)
{
currentSession = context.Items[CurrentSessionKey] as ISession;
}
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
if (context != null)
{
context.Items.Remove(CurrentSessionKey);
}
}
/// <summary>
/// セッション・ファクトリをクローズ
/// </summary>
public static void CloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
※自己責任で上のソースを自由に(完全フリー)ご利用ください。
使い方
using NHibernate.Utils;
...
ISession session = NHibernateHelper.GetCurrentSession();
...
Sponsored Link
- Relative Articles
- NHibernate のインストール&導入 - (2009/11/25 13:03)
- 初めてのNHibernate入門 サンプル - (2009/11/25 17:19)
- The IDbCommand and IDbConnection ... MySql.Data could not be found エラーについて - (2009/12/10 13:31)
- NHibernate データベースのDialect名一覧 - (2009/10/14 13:57)
- NHibernate の設定ファイルhibernate.cfg.xmlの記述例 - (2009/11/25 16:18)
- NHibernate マッピングの書き方 - (2009/11/25 17:04)
- NHibernate+C# Genericで汎用的なDAO を作成 - (2009/11/26 11:51)