NHibernateHelper

个人的NHibernateHelper工具类。支持泛型操作,使用session-per-request模式,绑定session到web上下文。
注意点是,无需在Application_BeginRequest加入session开启代码,session的开启是在第一次需要调用时,Application_EndRequest事件加入NhibernateHelper.CloseSession();关闭session。

public class NhibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;
        private static readonly NhibernateHelper nhelper = new NhibernateHelper();
  

        static NhibernateHelper()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }

        private NhibernateHelper()
        {

        }

        public static NhibernateHelper getInstance()
        {
            return nhelper;
        }
        //返回新开启的session,未绑定到上下文,需显式关闭
        public static ISession GetNewSession()
        {
            return sessionFactory.OpenSession();
        }

        public static IStatelessSession getStatelessSession()
        {
          return sessionFactory.OpenStatelessSession();
        }
        //返回绑定在当前上下文的session,如果上下文还没有session新开启并绑定
        public static ISession GetCurrentSession()
        {
            ISession session;
            try
            {

                if (CurrentSessionContext.HasBind(sessionFactory))
                {
                    session = sessionFactory.GetCurrentSession();
                }
                else
                {
                    session = sessionFactory.OpenSession();
                    CurrentSessionContext.Bind(session);
                }
                return session;
            }
            catch
            {
                throw;
            }
        }

        public static void CloseSession()
        {
            if (CurrentSessionContext.HasBind(sessionFactory))
            {
                ISession session = CurrentSessionContext.Unbind(sessionFactory);
                //session.Flush();
                session.Close();
            }
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }

        /// <summary>
        /// 根据主键查询一个实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T get<T>(object id)
        {
            ISession session = GetCurrentSession();
            return (T)session.Get(typeof(T), id);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>主键</returns>
        public object save(object entity)
        {
            ISession session = GetCurrentSession();
            object id = session.Save(entity);
            session.Flush();
            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        public void update(object entity)
        {
            ISession session = GetCurrentSession();
            session.Update(entity);
            session.Flush();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        public void delete(object entity)
        {
            ISession session = GetCurrentSession();
            using (ITransaction tx = session.BeginTransaction())
            {
                try
                {
                    session.Delete(entity);
                    tx.Commit();
                }
                catch (HibernateException)
                {
                    tx.Rollback();
                    throw;
                }
            }

        }

        /// <summary>
        /// 根据条件查询一个对象
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <param name="paramValues">查询条件里的参数值数组</param>
        /// <returns>一个对象T</returns>
        public T get<T>(String where, Object[] paramValues)
        {
            IList<T> list = find<T>(where, paramValues, null);
            if (list.Count >= 1)
                return list[0];
            else
                return default(T);
        }

        /// <summary>
        /// 查询对象
        /// </summary>
        /// <typeparam name="T">ilist</typeparam>
        /// <returns></returns>
        public virtual IList<T> find<T>()
        {
            ISession session = GetCurrentSession();
            return session.CreateCriteria(typeof(T)).List<T>();
        }

        /// <summary>
        /// 根据条件查询,排序方式查询
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <param name="paramValues">参数值</param>
        /// <param name="orderBy">排序字段加排序方式</param>
        /// <returns></returns>
        public IList<T> find<T>(String where, Object[] paramValues, String orderBy)
        {
            String hql = "from " + typeof(T).FullName;
            if (!string.IsNullOrEmpty(where))
                hql = hql + " where " + where;
            if (!string.IsNullOrEmpty(orderBy))
                hql = hql + " order by " + orderBy;
            return executeQuery<T>(hql, paramValues);
        }

        public IList<T> findWithPage<T>(String hql, int rowPage, int curPage)
        {
            ISession session = GetCurrentSession();
            IQuery query = session.CreateQuery(hql);
            return query.SetFirstResult(rowPage * (curPage - 1)).SetMaxResults(rowPage).List<T>();
        }

        /// <summary>
        /// 运行hql语句查询,返回list
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="hql">hql语句</param>
        /// <param name="values">参数值</param>
        /// <returns>IList</returns>
        public virtual IList<T> executeQuery<T>(String hql, Object[] values)
        {
            if (values != null && values.Length > 0 && StringUtils.getCountCharInString(hql, '?') != values.Length)
                throw new ArgumentException("hql语句需要的参数个数与数组参数内的元素个数不一致");

            ISession session = GetCurrentSession();
            IQuery query = session.CreateQuery(hql);
            if (values != null && values.Length > 0)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    query.SetParameter(i, values[i]);
                }
            }
            return query.List<T>();

        }

        /// <summary>
        /// 运行hql查询返回一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hql"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public virtual T executeQueryForObj<T>(String hql, Object[] values)
        {
            if (values != null && values.Length > 0 && StringUtils.getCountCharInString(hql, '?') != values.Length)
                throw new ArgumentException("hql语句需要的参数个数与数组参数内的元素个数不一致");

            ISession session = GetCurrentSession();
            IQuery query = session.CreateQuery(hql);
            if (values != null && values.Length > 0)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    query.SetParameter(i, values[i]);
                }
            }
            IList<T> l = query.List<T>();
            if (l != null && l.Count > 0)
            {
                return l[0];
            }
            else
            {
                return default(T);
            }

        }

        public virtual IList<Object> executeSqlQuery(String sql)
        {
            ISession session = GetCurrentSession();
            return session.CreateSQLQuery(sql).List<Object>();
        }

        public int execute(String hql)
        {
            ISession session = GetCurrentSession();
            using (ITransaction tx = session.BeginTransaction())
            {
                try
                {
                    IQuery query = session.CreateQuery(hql);
                    int count = query.ExecuteUpdate();
                    tx.Commit();
                    return count;
                }
                catch (HibernateException)
                {
                    tx.Rollback();
                    throw;
                }
            }
        }

        public void batchExecuteSql(List<String> hqlList)
        {
            if (hqlList.Count == 0)
                throw new ArgumentException();
            ISession session = GetCurrentSession();
            using (ITransaction tx = session.BeginTransaction())
            {
                try
                {
                    for (int i = 0; i < hqlList.Count; i++)
                    {
                        IQuery query = session.CreateSQLQuery(hqlList[i]);
                        int count = query.ExecuteUpdate();
                        if (i % 30 == 0)
                        {
                            session.Flush();
                            session.Clear();
                        }
                    }
                    tx.Commit();
                }
                catch (HibernateException)
                {
                    tx.Rollback();
                    throw;
                }
            
            }
        }

        public virtual int executeSql(String sql)
        {
            ISession session = GetCurrentSession();
            using (ITransaction tx = session.BeginTransaction())
            {
            try
            {
                ISQLQuery q = session.CreateSQLQuery(sql);
                int count = q.ExecuteUpdate();
                tx.Commit();
                return count;
            }
            catch (HibernateException)
            {
                tx.Rollback();
                throw;
            }
            
            }
        }
}

nhibernate配置选项<property name="current_session_context_class">web</property>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值