首页 > 代码库 > NHibernate学习

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大概就这么多了,接下来学习实体类映射。

 

NHibernate学习