NHibernate学习

2021-06-16 20:05

阅读:640

标签:this   containe   factory   created   UI   ssi   dcl   ase   manage   

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

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

 建立IRepository接口

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

(string command); }

 

建立Repository类

 public class Repository : IRepository
    {
        public ISessionFactory sessionFactory { get; set; }
        /// 
        /// 增加一个实体
        /// 
        /// 
        public void Add(T objectToAdd)
        {
            ISession session = GetSession();
            session.Save(objectToAdd);
            session.Flush();
        }
        /// 
        /// 增加多条实体
        /// 
        /// 
        public void AddList(IList 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();
            }
        }
        /// 
        /// 删除一条实体
        /// 
        /// 
        public void Delete(T objectToDelete)
        {
            ISession session = GetSession();
            session.Delete(objectToDelete);
            session.Flush();
        }
        /// 
        /// 删除多条实体
        /// 
        /// 
        public void DeleteList(IList 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();               
            }
        }
        /// 
        /// 更新一个实体
        /// 
        /// 
        public void Update(T objectToUpdate)
        {
            ISession session = GetSession();
            session.SaveOrUpdate(objectToUpdate);
            session.Flush();
        }
        /// 
        /// 更新多条实体
        /// 
        /// 
        public void UpdateList(IList 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();
            }
        }
        /// 
        /// 查询一条SQL语句
        /// 
        /// 
        /// 
        public ISQLQuery DTOQuery(string command)
        {
            ISession session = GetSession();
            var query = session.CreateSQLQuery(command);
            query.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(T)));
            return query;
        }
             
        /// 
        /// 查询所有的数据
        /// 
        /// 
        public IQueryable Query()
        {
            ISession session = GetSession();
            return session.Query();
        }
     
        /// 
        /// 查询总量
        /// 
        /// 
        /// 
        /// 
        public P SQLQuery

(string command) { P result; ISession session = GetSession(); var query = session.CreateSQLQuery(command); result = query.UniqueResult

(); return result; } ///

/// NHibernate中获取Session /// /// protected virtual ISession GetSession() { ISession session = this.sessionFactory.GetCurrentSession(); if (session==null) { session = this.sessionFactory.OpenSession(); } return session; } } /// /// ISession的扩展方法 /// public static class ExpandClass { public static IQueryable Query(this ISession session) { return new NhQueryable(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()
                .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;
        }

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

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

        /// 
        /// Unbind the current session of the session factory.
        /// 
        /// 
        /// 
        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;
        }

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

        private static IDictionary> CurrentFactoryMap;
    }

 

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

 

NHibernate学习

标签:this   containe   factory   created   UI   ssi   dcl   ase   manage   

原文地址:http://www.cnblogs.com/shuai7boy/p/7269928.html

上一篇:【nodejs】

下一篇:CSS 选择器


评论


亲,登录后才可以留言!