NHibernate帮助类


 using System;

 using NHibernate;

 using NHibernate.Cfg;

 using System.Collections;

 using System.Collections.Generic;

 using System.Reflection;

 

 namespace myCRM

 {

     public sealed class DBHelperNH

     {

         #region 变量定义

         [ThreadStatic]

         private static ISession threadLocalSession;

 

         private static ISessionFactory SessionFactory = null;

 

         private static ITransaction m_TransAction = null;

         private static ISession Session = null;

         private static bool isTransAction = false;

         #endregion

 

         #region 构造函数

         static DBHelperNH()

         {

             try

             {

                 string strHBConfigPath = System.Environment.CurrentDirectory + @"\myCRM.cfg.xml";

                 SessionFactory = new Configuration().Configure(strHBConfigPath).BuildSessionFactory();

             }

             catch (Exception ex)

             {

                 throw ex;

             }

         }

 

         #endregion

 

         #region 连接管理

         private static ISession CreatSession()

         {

             if (threadLocalSession == null || !threadLocalSession.IsOpen)

                 threadLocalSession = (SessionFactory != null) ? SessionFactory.OpenSession() : null;

 

             if (!threadLocalSession.IsConnected)

                 threadLocalSession.Reconnect();

 

             return threadLocalSession;

         }

         private static void CloseSession()

         {

             if (threadLocalSession != null)

             {

                 threadLocalSession.Close();

                 threadLocalSession = null;

             }

         }

 

         #endregion

 

         #region  封装函数

 

         #region 事务的操作控制

 

         public static void BeginTransAction()

         {

             try

             {

                 Session = CreatSession();

                 Session.Clear();

                 m_TransAction = Session.BeginTransaction();

                 isTransAction = true;

             }

             catch (Exception ex)

             {

                 throw ex;

             }

         }

         public static void CommitTransAction()

         {

             try

             {

                 m_TransAction.Commit();

             }

             catch (Exception ex)

             {

                 if (m_TransAction.IsActive) m_TransAction.Rollback();

                 throw ex;

             }

             finally

             {

                 isTransAction = false;

                 CloseSession();

             }

         }

 

         #endregion

 

         #region 基本数据的增删改查

 

         public static IList<T> FindAll<T>()

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 IList<T> lst = Session.CreateCriteria(typeof(T)).List<T>();

                 InitStatus<T>(lst);

 

                 return lst;

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

         public static IList<T> Find<T>(string strHQL)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 IList<T> lst = Session.CreateQuery(strHQL).List<T>();

                 InitStatus<T>(lst);

 

                 return lst;

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

 

         public static T Get<T>(object ID)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 T objT = Session.Get<T>(ID);

                 InitStatus<T>(objT);

 

                 return objT;

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

         public static T GetByHql<T>(string strHQL)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 T objT = Session.CreateQuery(strHQL).UniqueResult<T>();

                 InitStatus<T>(objT);

 

                 return objT;

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

 

         public static void Save<T>(T value)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 Session.Save(value);

                 Session.Flush();

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

         public static void Update<T>(T value)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 Session.Update(value);

                 Session.Flush();

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

         public static void SaveOrUpdate<T>(T value)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 Session.SaveOrUpdate(value);

                 Session.Flush();

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

         public static void Delete<T>(T value)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 Session.Delete(value);

                 Session.Flush();

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

 

         public static int ExcDML(string strDML)

         {

             try

             {

                 if (!isTransAction) Session = CreatSession();

                 int count = Session.CreateQuery(strDML).ExecuteUpdate();

 

                 return count;

             }

             finally

             {

                 if (!isTransAction) CloseSession();

             }

         }

 

         #endregion

 

         #region 实实体集合和单个实体对象状态操作

 

         /// <summary>

         /// 更新实体集合状态,状态:IsAdded,IsChanged,IsDeleted,全部置为false

         /// </summary>

         /// <typeparam name="T">实体类型</typeparam>

         /// <param name="lst">实体集合</param>

         public static void InitStatus<T>(IList<T> lst)

         {

             for (int i = 0; i < lst.Count; i++)

             {

                 Type t = lst[i].GetType();

                 try

                 {

                     t.GetProperty("IsAdded").SetValue(lst[i], false, null);

                     t.GetProperty("IsChanged").SetValue(lst[i], false, null);

                     t.GetProperty("IsDeleted").SetValue(lst[i], false, null);

                 }

                 catch (Exception)

                 { }

             }

         }

         /// <summary>

         /// 更新实体状态,状态:IsAdded,IsChanged,IsDeleted,全部置为false

         /// </summary>

         /// <typeparam name="T">实体类型</typeparam>

         /// <param name="value">实体对象</param>

         public static void InitStatus<T>(T value)

         {

             Type t = value.GetType();

             try

             {

                 t.GetProperty("IsAdded").SetValue(value, false, null);

                 t.GetProperty("IsChanged").SetValue(value, false, null);

                 t.GetProperty("IsDeleted").SetValue(value, false, null);

             }

             catch (Exception)

             { }

         }

 

         #endregion

 

         #region 公用方法集合

 

         /// <summary>

         /// 根据实体状态对实体容器进行增删改,状态:IsAdded,IsChanged,IsDeleted

         /// </summary>

         /// <typeparam name="T">实体类型</typeparam>

         /// <param name="lstIOC">实体数据容器</param>

         /// <returns>返回消息</returns>

         public static string SaveIOC<T>(IList<T> lstIOC)

         {

             int sum = lstIOC.Count, error = 0;

 

             string msg = "本地操作时间:\t" + DateTime.Now;

 

             if (sum == 0) return "没有需要操作的数据!";

             for (int i = 0; i < lstIOC.Count; i++)

             {

                 Type t = lstIOC[i].GetType();

                 try

                 {

                     if ((bool)t.GetProperty("IsAdded").GetValue(lstIOC[i], null)) Save<T>(lstIOC[i]);

                     if ((bool)t.GetProperty("IsChanged").GetValue(lstIOC[i], null)) Update<T>(lstIOC[i]);

                     if ((bool)t.GetProperty("IsDeleted").GetValue(lstIOC[i], null)) Delete<T>(lstIOC[i]);

                 }

                 catch (Exception ex)

                 {

                     error++;

                     msg += "\n发现错误:\t" + ex.Message;

                 }

             }

 

             msg += "\n操作数/成功数:\t" + sum + "/" + (sum - error);

 

             return msg;

         }

 

         #endregion

 

         #endregion

 

     }

 }


这是我在项目中用的一个帮助类,经验水平都不高,还请各位高手分析有没有不恰当的地方啊,这个和mygeneration代码生成器配合

mygeneration代码生成器模板NHibernate

不得已放到首页,敬请谅解。这个类和模板如果大家觉得合适,欢迎推广使用~

你可能感兴趣的:(Hibernate)