遗忘的代码

在编程中寻找艺术,享受新的体验。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、创建查询条件,条件为一个ICreterion的列表

        ///
        /// 创建Criteria(不含order,因为获取总数的时候,为了性能考虑,不加order)
        ///
        /// 类型
        /// ICriterion列表
        ///
        public ICriteria CreateCriteria(Type t, List list)
        {
            ICriteria criteria = Session.CreateCriteria(t);

            if (list != null && list.Count > 0)
            {
                foreach (ICriterion c in list)
                {
                    criteria.Add(c);
                }
            }

            return criteria;
        }

2、分页查询

        ///
        ///获取排序的pageInfo
        ///
        /// 类型
        /// ICriterion列表
        /// 升序?true:false
        /// 排序字段
        ///
        public PageInfo getOrderdPagedListByCriteria(PageInfo pageInfo,Type t, List list, bool isAsc, string orderBy)
        {
           ICriteria c= CreateCriteria(t, list);//拼接查询条件

           int startNum = pageInfo.CurrentPage * pageInfo.PageSize;

//创建一个同样的ICriteria对象,不然执行总数查询之后,ICriteria的条件依然还是总数查询,下边的结果查询会出错。

           ICriteria pageCriteria = CriteriaTransformer.Clone(c);

//执行结果查询,Projections对象会投影到一个新的查询,包含AVG、sum、count等等
           pageInfo.RowCount = int.Parse(pageCriteria.SetProjection(Projections.RowCount()).UniqueResult().ToString());

 

//执行完总数查询之后,就给之前的ICriteria对象创建排序规则

           if (isAsc)
               c.AddOrder(new Order(orderBy, true));
           else
               c.AddOrder(new Order(orderBy, false));

//创建完排序规则之后,执行数据查询
           pageInfo.Results = c.SetFirstResult(startNum).SetMaxResults(pageInfo.PageSize).List().ToList();

           return pageInfo;
        }

 

注:PageInfo是一个分页类

 ///
        /// 结果
        ///
        public List Results { get; set; }

        ///
        /// 当前页码
        ///
        public int CurrentPage { get; set; }

        ///
        /// 页总数(一共有多少页)
        ///
        public int PageCount
        {
            get
            {
                if (RowCount == 0)
                {
                    return 1;
                }
                else
                {
                    return (int)Math.Ceiling(RowCount / (double)PageSize);
                }
            }
            private set
            {
                this.PageCount = value;
            }
        }

        ///
        /// 总记录数
        ///
        public int RowCount { get; set; }

        ///
        /// 每页记录数
        ///
        private int pagesize;
        public int PageSize
        {
            get { return pagesize; }
            set { pagesize = value; }
        }

            
    }

posted on 2015-02-06 15:41  遗忘的代码  阅读(208)  评论(0编辑  收藏  举报