Exemple #1
0
        /// <summary>
        /// Gets the entity list from respersitory.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expressions">The criterion expressions,for example:new ICriterion[]{Restriction.Eq("AField","xy")}.</param>
        /// <param name="orders">The orders.</param>
        /// <returns></returns>
        public IList <T> GetList <T>(Hib.Criterion.ICriterion expression, params Hib.Criterion.Order[] orders)
        {
            try
            {
                OpenConnect();
                Hib.ICriteria criteria = _Session.CreateCriteria(typeof(T));
                if (expression != null)
                {
                    criteria.Add(expression);
                }

                foreach (Hib.Criterion.Order o in orders)
                {
                    criteria.AddOrder(o);
                }
                return(criteria.List <T>());
            }
            catch (Exception ex)
            {
                LogExepttion(ex);
                throw;
            }
            finally
            {
                Disconnect();
            }
        }
Exemple #2
0
 /// <summary>
 /// Gets the entity list from respersitory.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="expressions">The criterion expressions,for example:new ICriterion[]{Restriction.Eq("AField","xy")}.</param>
 /// <param name="orders">The orders.</param>
 /// <returns></returns>
 public IList <T> GetList <T>(Hib.Criterion.ICriterion[] expressions, string associatePath, string alias, params Hib.Criterion.Order[] orders)
 {
     try
     {
         OpenConnect();
         Hib.ICriteria criteria = _Session.CreateCriteria(typeof(T));
         criteria.CreateAlias(associatePath, alias);
         if (expressions != null)
         {
             foreach (Hib.Criterion.ICriterion exp in expressions)
             {
                 criteria.Add(exp);
             }
         }
         foreach (Hib.Criterion.Order o in orders)
         {
             criteria.AddOrder(o);
         }
         return(criteria.List <T>());
     }
     catch (Exception ex)
     {
         LogExepttion(ex);
         throw;
     }
     finally
     {
         Disconnect();
     }
 }
Exemple #3
0
        /// <summary>
        /// 根据查询条件创建Criteria
        /// </summary>
        /// <param name="session"></param>
        /// <param name="searchExpression"></param>
        /// <param name="searchOrders"></param>
        /// <param name="hasCollection"></param>
        /// <returns></returns>
        public static NHibernate.ICriteria CreateCriteria(NHibernate.ISession session, ISearchExpression searchExpression,
                                                          IList <ISearchOrder> searchOrders, ref bool hasCollection)
        {
            hasCollection = false;
            int paramCnt = 0;

            NHibernate.ICriteria           criteria = session.CreateCriteria(typeof(T), "Current");
            Dictionary <string, ICriteria> aliases  = new Dictionary <string, ICriteria>();

            aliases.Add("Current", criteria);

            NHibernate.Criterion.ICriterion criterion = GetCriterion(session.SessionFactory, ref criteria, aliases, searchExpression, ref hasCollection, ref paramCnt);
            if (criterion != null)
            {
                criteria.Add(criterion);
            }
            if (paramCnt > 2100)
            {
                throw new NotSupportedException("您输入的参数过多,系统最多只支持2100个参数!");
            }

            if (searchOrders != null)
            {
                foreach (ISearchOrder so in searchOrders)
                {
                    criteria.AddOrder(GetOrder(ref criteria, aliases, so));
                }
            }

            return(aliases["Current"]);
        }
 /// <summary>
 /// Returns to nhibernate the type of the parameters.
 /// I need only one operator.
 /// </summary>
 /// <param name="criteria"></param>
 /// <param name="criteriaQuery"></param>
 /// <returns></returns>
 public override NHibernate.Engine.TypedValue[] GetTypedValues(
     NHibernate.ICriteria criteria,
     NHibernate.Criterion.ICriteriaQuery criteriaQuery)
 {
     return(new TypedValue[] {
         new TypedValue(GetITypeFromCLRType(mValueToCompareTo.GetType()), mValueToCompareTo, EntityMode.Poco)
     });
 }
 /// <summary>
 /// Returns to nhibernate the type of the parameters.
 /// I need only one operator.
 /// </summary>
 /// <param name="criteria"></param>
 /// <param name="criteriaQuery"></param>
 /// <returns></returns>
 public override NHibernate.Engine.TypedValue[] GetTypedValues(
     NHibernate.ICriteria criteria,
     NHibernate.Expressions.ICriteriaQuery criteriaQuery)
 {
     return(new TypedValue[] {
         new TypedValue(GetITypeFromCLRType(mValueToCompareTo.GetType()), mValueToCompareTo)
     });
 }
Exemple #6
0
        private System.Collections.IEnumerable GetData(ISearchExpression searchExpression, IList <ISearchOrder> searchOrders, NHibernate.ISession session)
        {
            NHibernate.ICriteria criteria = CreateCriteria(session, searchExpression, searchOrders, ref m_hasCollection);

            OnCriteriaCreated(criteria);

            return(criteria.List <T>());
            //return criteria.Future<T>();
        }
Exemple #7
0
        private void GetData(ISearchExpression searchExpression, IList <ISearchOrder> searchOrders,
                             NHibernate.ISession session, ActionableList <object> actionList)
        {
            NHibernate.ICriteria criteria = CreateCriteria(session, searchExpression, searchOrders, ref m_hasCollection);

            OnCriteriaCreated(criteria);

            criteria.List(actionList);
        }
Exemple #8
0
        public static String GetCritionSql(NHibernate.ICriteria criteria)
        {
            var criteriaImpl = (CriteriaImpl)criteria;
            var sessionImpl  = (SessionImpl)criteriaImpl.Session;
            var factory      = (SessionFactoryImpl)sessionImpl.SessionFactory;
            var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);
            var loader       = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters);

            var originalSql = loader.SqlString.ToString();

            if (loader.Translator.CollectedParameters.Count > 0)
            {
                foreach (var param in loader.Translator.CollectedParameters)
                {
                    int paramIndex = originalSql.IndexOf("?");
                    if (param.Type.GetType().Name == "StringType" ||
                        param.Type.GetType().Name == "DateTimeType" ||
                        param.Type.GetType().Name == "DateTime2Type" ||
                        param.Type.GetType().Name == "GuidType")
                    {
                        originalSql = originalSql.Substring(0, paramIndex) + "'" + param.Value + "'" + originalSql.Substring(paramIndex + 1);
                    }
                    else
                    {
                        originalSql = originalSql.Substring(0, paramIndex) + param.Value + originalSql.Substring(paramIndex + 1);
                    }
                }
            }
            var fromIndex      = 0;
            var lastCommaIndex = 0;

            while (true)
            {
                fromIndex = originalSql.IndexOf("from", lastCommaIndex, StringComparison.OrdinalIgnoreCase);
                var asIndex = originalSql.IndexOf(" as ", lastCommaIndex, StringComparison.OrdinalIgnoreCase);

                if (asIndex < 0 || asIndex > fromIndex)
                {
                    break;
                }
                else
                {
                    lastCommaIndex = originalSql.IndexOf(",", lastCommaIndex + 1, StringComparison.OrdinalIgnoreCase);
                    if (lastCommaIndex >= 0 && lastCommaIndex < fromIndex)
                    {
                        originalSql    = originalSql.Remove(asIndex, lastCommaIndex - asIndex);
                        lastCommaIndex = asIndex;
                    }
                    else
                    {
                        originalSql = originalSql.Remove(asIndex + 1, fromIndex - asIndex - 1);
                        break;
                    }
                }
            }
            return(originalSql);
        }
        /// <summary>
        /// 读取全部
        /// </summary>
        /// <returns></returns>
        public IList <T> GetAll(int startIndex, int maxRows, string sortedBy)
        {
            using (var rep = new Repository(this.RepositoryCfgName))
            {
                rep.BeginTransaction();
                NHibernate.ICriteria cri = rep.Session.CreateCriteria(typeof(T));

                var ret = GetAll(cri, startIndex, maxRows, sortedBy);

                rep.CommitTransaction();
                return(ret);
            }
        }
 /// <summary>
 /// 获得分页读取的总数量
 /// </summary>
 /// <param name="cri"></param>
 /// <returns></returns>
 protected int GetAllCount(NHibernate.ICriteria cri)
 {
     System.Collections.IList list = cri
                                     .SetProjection(NHibernate.Criterion.Projections.RowCount())
                                     .List();
     if (list.Count > 0)
     {
         return((int)list[0]);
     }
     else
     {
         return(0);
     }
 }
Exemple #11
0
 /// <summary>
 /// Gets the distict list.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="distictPropertys">The distict propertys.</param>
 /// <param name="expressions">The expressions.</param>
 /// <param name="orders">The orders.</param>
 /// <returns></returns>
 public IList <object[]> GetDistinctList <T>(string[] distictPropertys, Hib.Criterion.ICriterion[] expressions, params Hib.Criterion.Order[] orders)
 {
     try
     {
         OpenConnect();
         Hib.ICriteria criteria = _Session.CreateCriteria(typeof(T));
         if (distictPropertys != null)
         {
             ProjectionList projects = Projections.ProjectionList();
             foreach (string p in distictPropertys)
             {
                 projects.Add(Projections.Property(p));
             }
             criteria.SetProjection(Projections.Distinct(projects));
         }
         else
         {
             throw new Exception("the disctinct property can't be null.");
         }
         if (expressions != null)
         {
             foreach (Hib.Criterion.ICriterion exp in expressions)
             {
                 criteria.Add(exp);
             }
         }
         foreach (Hib.Criterion.Order o in orders)
         {
             criteria.AddOrder(o);
         }
         return(criteria.List <object[]>());
     }
     catch (Exception ex)
     {
         LogExepttion(ex);
         throw;
     }
     finally
     {
         Disconnect();
     }
 }
Exemple #12
0
        /// <summary>
        /// Prepare the given Criteria object, applying cache settings and/or
        /// a transaction timeout.
        /// </summary>
        /// <remarks>
        /// <para>Note that for NHibernate 1.2 this only works if the
        /// implementation is of the type CriteriaImpl, which should generally
        /// be the case.  The SetFetchSize method is not available on the
        /// ICriteria interface
        /// </para>
        /// <para>This is a no-op for NHibernate 1.0.x since
        /// the SetFetchSize method is not on the ICriteria interface and
        /// the implementation class is has internal access.
        /// </para>
        /// <para>To remove the method completely for Spring's NHibernate 1.0
        /// support while reusing code for NHibernate 1.2 would not be
        /// possible.  So now this ineffectual operation is left in tact for
        /// NHibernate 1.0.2 support.</para>
        /// </remarks>
        /// <param name="criteria">The criteria object to prepare</param>
        public void PrepareCriteria(ICriteria criteria)
        {
            if (CacheQueries)
            {
                criteria.SetCacheable(true);
                if (QueryCacheRegion != null)
                {
                    criteria.SetCacheRegion(QueryCacheRegion);
                }
            }



            if (FetchSize > 0)
            {
                //TODO see if we can optimize performance.
                //CriteriaImpl is internal in NH 1.0.x
                object[] args = new object[] { FetchSize };
                try
                {
                    Type t = TypeResolutionUtils.ResolveType("NHibernate.Impl.CriteriaImpl, NHibernate");
                    if (t != null)
                    {
                        t.InvokeMember("SetFetchSize", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
                                       | BindingFlags.InvokeMethod,
                                       null, criteria, args);
                    }
                }
                catch (TypeLoadException e)
                {
                    log.Warn("Can't set FetchSize for ICriteria", e);
                }
            }

            if (MaxResults > 0)
            {
                criteria.SetMaxResults(MaxResults);
            }

            SessionFactoryUtils.ApplyTransactionTimeout(criteria, SessionFactory);
        }
 /// <summary>
 /// 分页读取
 /// </summary>
 /// <param name="cri"></param>
 /// <param name="startIndex"></param>
 /// <param name="maxRows"></param>
 /// <param name="sortedBy"></param>
 /// <returns></returns>
 protected IList <T> GetAll(NHibernate.ICriteria cri, int startIndex, int maxRows, string sortedBy)
 {
     cri.SetFirstResult(startIndex);
     if (maxRows > 0)
     {
         cri.SetMaxResults(maxRows);
     }
     if (!string.IsNullOrEmpty(sortedBy))
     {
         string[] ss = sortedBy.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
         if (ss.Length == 2 && ss[1].ToUpper() == "DESC")
         {
             cri.AddOrder(new NHibernate.Criterion.Order(ss[0], false));
         }
         else
         {
             cri.AddOrder(new NHibernate.Criterion.Order(ss[0], true));
         }
     }
     return(cri.List <T>());
 }
        /// <summary>
        /// This is the real core function that build the fragment of sql needed
        /// to build the criteria
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="criteriaQuery"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override NHibernate.SqlCommand.SqlString ToSqlString(
            NHibernate.ICriteria criteria,
            NHibernate.Expressions.ICriteriaQuery criteriaQuery,
            IDictionary <string, IFilter> enabledFilters)
        {
            //retrieve with projection the real name of the property.
            String[] PropertyColumn = criteriaQuery.GetColumnsUsingProjection(
                criteria, (String)mSqlFunctionParameter[mPropertyNamePosition]);
            NHibernate.Dialect.Dialect dialect = criteriaQuery.Factory.Dialect;
            mSqlFunctionParameter[mPropertyNamePosition] = PropertyColumn[0];
            if (!dialect.Functions.ContainsKey(mFunction))
            {
                //throw new ApplicationException("Current dialect does not support " + mFunction + " function");
                //Todo for now try to set the function but without the dialect.
                return(CreateQueryString(
                           BuildUnknownExpression(mFunction, mSqlFunctionParameter)));
            }
            ISQLFunction func             = (ISQLFunction)dialect.Functions[mFunction];
            String       functionResolved = func.Render(mSqlFunctionParameter, criteriaQuery.Factory);

            //Now we have the cast operation required.
            return(CreateQueryString(functionResolved));
        }
        public IList <SystemUser> GetByRestrictions(IDictionary <string, string> restrictions, string orderBy, bool ascending, int?limit)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                NHibernate.
                ICriteria criteria = session.CreateCriteria <SystemUser>();
                foreach (KeyValuePair <string, string> pair in restrictions)
                {
                    criteria = criteria.Add(Restrictions.Eq(pair.Key, pair.Value));
                }

                if (limit != null)
                {
                    criteria = criteria.SetMaxResults((int)limit);
                }

                if (orderBy != null)
                {
                    criteria = criteria.AddOrder(new Order(orderBy, ascending));
                }

                return(criteria.List <SystemUser>());
            }
        }
Exemple #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="criteria"></param>
        protected void OnCriteriaCreated(NHibernate.ICriteria criteria)
        {
            if (this.EagerFetchs != null)
            {
                foreach (string s in this.EagerFetchs)
                {
                    criteria = criteria.SetFetchMode(s, FetchMode.Eager);
                }
            }

            if (EnablePage)
            {
                criteria = criteria.SetFirstResult(FirstResult);
                if (MaxResult != -1)
                {
                    criteria = criteria.SetMaxResults(MaxResult);
                }
            }

            if (IsResultDistinct || m_hasCollection)
            {
                criteria = criteria.SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer());
            }
        }
 public ICollection <T> FindAll(NHibernate.ICriteria criteria)
 {
     return(criteria.List <T> ());
 }
Exemple #18
0
 /// <summary>
 /// 设置查询条件
 /// </summary>
 public abstract void SetCriteria(NHibernate.ICriteria criteria);
 public ICollection <T> FindAll(NHibernate.ICriteria criteria, int firstResult, int numberOfResults)
 {
     return(criteria.SetFirstResult(firstResult).SetMaxResults(numberOfResults).List <T> ());
 }
Exemple #20
0
        /// <summary>
        /// Prepare the given Criteria object, applying cache settings and/or
        /// a transaction timeout.
        /// </summary>
        /// <remarks>
        /// <para>Note that for NHibernate 1.2 this only works if the
        /// implementation is of the type CriteriaImpl, which should generally
        /// be the case.  The SetFetchSize method is not available on the
        /// ICriteria interface
        /// </para>
        /// <para>This is a no-op for NHibernate 1.0.x since
        /// the SetFetchSize method is not on the ICriteria interface and
        /// the implementation class is has internal access.
        /// </para>
        /// <para>To remove the method completely for Spring's NHibernate 1.0 
        /// support while reusing code for NHibernate 1.2 would not be 
        /// possible.  So now this ineffectual operation is left in tact for
        /// NHibernate 1.0.2 support.</para>
        /// </remarks>
        /// <param name="criteria">The criteria object to prepare</param>
        public void PrepareCriteria(ICriteria criteria)
        {
            if (CacheQueries)
            {
                criteria.SetCacheable(true);
                if (QueryCacheRegion != null)
                {
                    criteria.SetCacheRegion(QueryCacheRegion);
                }
            }



            if (FetchSize > 0)
            {
                //TODO see if we can optimize performance.
                //CriteriaImpl is internal in NH 1.0.x
                object[] args = new object[] { FetchSize };
                try
                {
                    Type t = TypeResolutionUtils.ResolveType("NHibernate.Impl.CriteriaImpl, NHibernate");
                    if (t != null)
                    {
                        t.InvokeMember("SetFetchSize", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
                                                       | BindingFlags.InvokeMethod,
                                       null, criteria, args);
                    }
                }
                catch (TypeLoadException e)
                {
                    log.Warn("Can't set FetchSize for ICriteria", e);
                }
            }
            
            if (MaxResults > 0)
            {
                criteria.SetMaxResults(MaxResults);
            }

            SessionFactoryUtils.ApplyTransactionTimeout(criteria, SessionFactory);
        }
Exemple #21
0
 private int GetCount(ISearchExpression searchExpression, NHibernate.ISession session)
 {
     NHibernate.ICriteria criteria2 = CreateCriteria(session, searchExpression, null, ref m_hasCollection);
     criteria2.SetProjection(NHibernate.Criterion.Projections.RowCount());
     return((int)criteria2.UniqueResult()); // criteria2.FutureValue<int>().Value;
 }