NHibernate学习

紧接上篇博文继续学习(PS:很多代码我就不重复了,在上篇博文的基础上开始学习NHibernate吧~)

代码还是像往常一样在Word里面总结了,这里就直接Copy,Copy

建立IRepository接口

public interface IRepository<T>
    {
        void Add(T objectToAdd);
        void AddList(IList<T> list);
        void Delete(T objectToDelete);
        void DeleteList(IList<T> list);
        void Update(T objectToUpdate);
        void UpdateList(IList<T> list);
        IQueryable<T> Query();
        ISQLQuery DTOQuery(string command);
        /// <summary>
        /// 返回特定的数据 和当前的Repository中对象可以不一致

        P SQLQuery<P>(string command);
}

建立Repository类

 public class Repository<T> : IRepository<T>
    {
        public ISessionFactory sessionFactory { get; set; }
        /// <summary>
        /// 增加一个实体
        /// </summary>
        /// <param name="objectToAdd"></param>
        public void Add(T objectToAdd)
        {
            ISession session = GetSession();
            session.Save(objectToAdd);
            session.Flush();
        }
        /// <summary>
        /// 增加多条实体
        /// </summary>
        /// <param name="list"></param>
        public void AddList(IList<T> list)
        {
            if (list==null||list.Count==0)
            {
                return;
            }
            var session = GetSession();
            using (var tran = session.BeginTransaction())
            {
                foreach (var item in list)
                {
                    session.Save(item);
                }
                tran.Commit();
            }
        }
        /// <summary>
        /// 删除一条实体
        /// </summary>
        /// <param name="objectToDelete"></param>
        public void Delete(T objectToDelete)
        {
            ISession session = GetSession();
            session.Delete(objectToDelete);
            session.Flush();
        }
        /// <summary>
        /// 删除多条实体
        /// </summary>
        /// <param name="list"></param>
        public void DeleteList(IList<T> list)
        {
            if (list==null||list.Count==0)
            {
                return;
            }
            var session = GetSession();
            using (var tran=session.BeginTransaction())
            {
                foreach (var item in list)
                {
                    session.Delete(item);
                }
                tran.Commit();
            }
        }
        /// <summary>
        /// 更新一个实体
        /// </summary>
        /// <param name="objectToUpdate"></param>
        public void Update(T objectToUpdate)
        {
            ISession session = GetSession();
            session.SaveOrUpdate(objectToUpdate);
            session.Flush();
        }
        /// <summary>
        /// 更新多条实体
        /// </summary>
        /// <param name="list"></param>
        public void UpdateList(IList<T> list)
        {
            if (list == null || list.Count == 0)
            {
                return;
            }
            var session = GetSession();
            using (var tran = session.BeginTransaction())
            {
                foreach (var item in list)
                {
                    session.Update(item);
                }
                tran.Commit();
            }
        }
        /// <summary>
        /// 查询一条SQL语句
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public ISQLQuery DTOQuery(string command)
        {
            ISession session = GetSession();
            var query = session.CreateSQLQuery(command);
            query.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(T)));
            return query;
        }

        /// <summary>
        /// 查询所有的数据
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> Query()
        {
            ISession session = GetSession();
            return session.Query<T>();
        }

        /// <summary>
        /// 查询总量
        /// </summary>
        /// <typeparam name="P"></typeparam>
        /// <param name="command"></param>
        /// <returns></returns>
        public P SQLQuery<P>(string command)
        {
            P result;
            ISession session = GetSession();
            var query = session.CreateSQLQuery(command);
            result = query.UniqueResult<P>();
            return result;
        }

         /// <summary>
         /// NHibernate中获取Session
         /// </summary>
         /// <returns></returns>
        protected virtual ISession GetSession()
        {
            ISession session = this.sessionFactory.GetCurrentSession();
            if (session==null)
            {
                session = this.sessionFactory.OpenSession();
            }
            return session;
        }

    }
    /// <summary>
    /// ISession的扩展方法
    /// </summary>
    public static class ExpandClass
    {
        public static IQueryable<T> Query<T>(this ISession session)
        {
            return new NhQueryable<T>(session.GetSessionImplementation());
        }
}

写IWindsorInstaller继承类

public class NHibernateInstaller : IWindsorInstaller
    {

        public string SQL = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            //将IRepository和Repository关联
            container.Register(Component.For(typeof(IRepository<>))
                .ImplementedBy(typeof(Repository<>))
                .LifeStyle.HybridPerWebRequestTransient()
                );

            container.Register(Component.For<ISessionFactory>()
                .UsingFactoryMethod(k=>BuildSessionFactory(SQL))
                );
        }
        public ISessionFactory BuildSessionFactory(string factoryKey)
        {
            var config = Fluently.Configure()
                  .Database
                  (
                        MsSqlConfiguration.MsSql2008.DefaultSchema("dbo").ConnectionString(factoryKey)
                        .ShowSql()
                  )
                  .CurrentSessionContext(typeof(LazySessionContext).AssemblyQualifiedName
                  );

            var sessionFactory = config.BuildSessionFactory();
            return sessionFactory;
        }
    }

上面用到一个LazySessionContext类

 public class LazySessionContext : ICurrentSessionContext
    {
        private readonly ISessionFactoryImplementor factory;
        private const string CurrentSessionContextKey = "NHibernateCurrentSession";

        public LazySessionContext(ISessionFactoryImplementor factory)
        {
            this.factory = factory;
        }

        /// <summary>
        /// Retrieve the current session for the session factory.
        /// </summary>
        /// <returns></returns>
        public ISession CurrentSession()
        {
            Lazy<ISession> initializer;
            var currentSessionFactoryMap = GetCurrentFactoryMap();
            if (currentSessionFactoryMap == null ||
                !currentSessionFactoryMap.TryGetValue(factory, out initializer))
            {
                return null;
            }
            return initializer.Value;
        }

        /// <summary>
        /// Bind a new sessionInitializer to the context of the sessionFactory.
        /// </summary>
        /// <param name="sessionInitializer"></param>
        /// <param name="sessionFactory"></param>
        public static void Bind(Lazy<ISession> sessionInitializer, ISessionFactory sessionFactory)
        {
            var map = GetCurrentFactoryMap();
            map[sessionFactory] = sessionInitializer;
        }

        /// <summary>
        /// Unbind the current session of the session factory.
        /// </summary>
        /// <param name="sessionFactory"></param>
        /// <returns></returns>
        public static ISession UnBind(ISessionFactory sessionFactory)
        {
            var map = GetCurrentFactoryMap();
            var sessionInitializer = map[sessionFactory];
            map[sessionFactory] = null;
            if (sessionInitializer == null || !sessionInitializer.IsValueCreated) return null;
            return sessionInitializer.Value;
        }

        /// <summary>
        /// Provides the CurrentMap of SessionFactories.
        /// If there is no map create/store and return a new one.
        /// </summary>
        /// <returns></returns>
        private static IDictionary<ISessionFactory, Lazy<ISession>> GetCurrentFactoryMap()
        {
            IDictionary<ISessionFactory, Lazy<ISession>> currentFactoryMap = null;
            if (HttpContext.Current != null)
            {
                currentFactoryMap = (IDictionary<ISessionFactory, Lazy<ISession>>)
                                        HttpContext.Current.Items[CurrentSessionContextKey];
                if (currentFactoryMap == null)
                {
                    currentFactoryMap = new Dictionary<ISessionFactory, Lazy<ISession>>();
                    HttpContext.Current.Items[CurrentSessionContextKey] = currentFactoryMap;
                }
            }
            else //为了application Job 执行,由于Job执行时没有HttpContext.Current
            {
                if (CurrentFactoryMap == null)
                {
                    CurrentFactoryMap = new Dictionary<ISessionFactory, Lazy<ISession>>();
                }
                currentFactoryMap = CurrentFactoryMap;
            }
            return currentFactoryMap;
        }

        private static IDictionary<ISessionFactory, Lazy<ISession>> CurrentFactoryMap;
    }

好了,NHibernate大概就这么多了,接下来学习实体类映射。

时间: 2024-08-08 09:39:20

NHibernate学习的相关文章

NHibernate学习系列一

NHibernate是一个面向.NET环境的对象/关系数据库映射工具.对象/关系数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去. 优点: (1)NHibernate不仅仅管理.NET类到数据库表的映射(包括.NET 数据类型到SQL数据类型的映射),还提供数据查询和获取数据的方法,可以大幅度减少开发时人工使用SQL和ADO.NET处理数据的时间. (2)面向对象:NHiberante的使

NHibernate学习笔记—1、构建NHibernate应用程序

下周就去办理离职手续了,之前没有使用过NHibernate,只知道NHibernate是一种ORM框架,但是听说新公司是使用NHibernate在做项目,所以,我就网上找资料学习一下NHibernate,在此以笔记的形式,记录自己的学习过程,一来供自己以后备忘用,而来希望对同样准备学习NHibernate的同行门有所帮助或提供借鉴. 什么是Nhibernate? NHibernate是一个面向.NET环境的对象/关系数据库映射工具.对象/关系数据库映射(object/relational map

Nhibernate学习教程(1)-- 开篇有益

NHibernate之旅(1):开篇有益 本节内容 NHibernate是什么 NHibernate的架构 NHibernate资源 欢迎加入NHibernate中文社区 作者注:2009-11-06已更新 NHibernate开篇有益 学习NHibernate有一段时间了,打算做个阶段性总结,就萌生了这个系列,这个系列参考NHibernate官方文档和Steve  Bohlen的NHibernate之夏视频教程.作为开篇,首先了解多少人在使用NHibernate,先搞清楚NHibernate是

NHibernate学习(零)-本次学习遇到的错误汇总

问题一: "System.TypeInitializationException"类型的未经处理的异常在 KimismeDemo.exe 中发生 其他信息: "NHibernate.Cfg.Configuration"的类型初始值设定项引发异常. 解决方式: 在NH配置文件中,一下节点必须是configuration下的第一个子节点 <configSections>     <section name="hibernate-configu

简单的NHibernate学习笔记

NHibernate是.NET平台下的ORM框架,与ADO.NET一样实现项目中数据库与项目系统的交互. 1.首先要用NHibernate框架就要有第三方的dll库来作为支持,附上百度云下载地址:(链接:http://pan.baidu.com/s/1dD2KRvz 密码:50fb) 2.新建一个类库项目 引入NHibernate库中的dll文件: 新建一个试题类People.cs: 注意这里每个属性要加virtual关键字 然后配置一个实体类的映射文件 文件名取名为people.hbm.xml

NHibernate学习教程(6)--事务Transactions

本节内容 事务概述 1.新建对象 [测试成功提交] [测试失败回滚] 2.删除对象 3.更新对象 4.保存更新对象 结语 上一篇我们介绍了NHibernate中的Insert, Update,  Delete操作,这篇我们来看看NHibernate中的事务.你通过它可以提交或者回滚你的操作. 事务概述 1.NHibernate中的事务(Transactions) 简单描述:要求ISession使用事务:做一些操作:提交或者回滚事务. 写成代码就像这样: ITransaction tx = _se

Nhibernate学习教程(2)-- 第一个NHibernate程序

NHibernate之旅(2):第一个NHibernate程序 本节内容 开始使用NHibernate 1.获取NHibernate 2.建立数据库表 3.创建C#类库项目 4.设计Domain 4-1.设计持久化类 4-2.编写映射文件 5.数据访问层 5-1.辅助类 5-2.编写操作 6.数据访问层的测试 6-1.配置NHibernate 6-2.测试 结语 开始使用NHibernate 我们亲自动手,一步一步搭建一个NHibernate程序来,我以一个实际场景电子交易程序来模拟,客户/订单

NHibernate 学习笔记(一)

NHibernate 的简介: NHibernate是一个面向.NET环境的对象/关系数据库映射工具.对象/关系数据库映射(object/relational mapping (ORM))这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去. NHibernate不仅仅管理.NET类到数据库表的映射(包括.NET数据类型到SQL数据类型的映射),还提供数据查询和获取数据的方法,可以大幅度减少开发时人工使用SQL和ADO.NET处理数据的时间. NHibernate

NHibernate学习总结

给出几个问题总能让你带着思考去看这个文档,从中也许能够获得一些好处. 1.NHibernate是什么? NHibernate是一个面向.NET环境的对象/关系数据库映射框架(工具).对象/关系数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去 . 如下图所示: O:Object也就是class类,用于业务处理时的Domain类.如上图中的Customer类 R:就是数据库中的关系,也就是一张