Criteria 查询是其中查询的一种,其特点是,以各种API来进行查询,大家都不喜欢以字符串形式来查询,比如HQL.这种查询也犹如linq的where,any,等子查询。非常的方便,一般大家会首选此查询.
一.Criteria以ICriteria接口的方式链接(chain)方式编写,首先是创建ICriteria接口
ICriteria criteria = session.CreateCriteria(typeof(Student));
顾名思义ICriteria的主要任务当然就是查询了,下面来看下比较重要的。
1.查询表达式
ICriterion是一个查询条件结果集,可以通过ICriteria的Add方法添加条件
(2)表示式写法(以实例方式声明一个表达式)
using (ISession session = this.OpenSession()) { ICriteria criteria = session.CreateCriteria(typeof(Student), "c"); criteria.Add(new LikeExpression(Projections.Property("Name"), "John", MatchMode.Anywhere)); Assert.AreEqual(1, criteria.List().Count); }
(2)使用投影查询(以Restriction快捷创建一个表达式,Restriction提供了创建表达式的快捷方式)
ICriteria criteria = session.CreateCriteria(typeof(Student), "c"); criteria.Add(Restrictions.Like(Projections.Constant("Name"), "John", MatchMode.Anywhere));
如
public static AbstractCriterion IsNull(IProjection projection) { return new NullExpression(projection); }
public static AbstractCriterion Between(string propertyName, object lo, object hi) { return new BetweenExpression(propertyName, lo, hi); }
下列为常用的查询
1.排序
ICriteria criteria = session.CreateCriteria(typeof(Student), "c"); criteria .AddOrder(Order.Asc( Projections.Conditional( Restrictions.Eq("StudentNumber", (long)1), Projections.Constant(0), Projections.Constant(1) )));
2.转换结果为数字
ICriteria countCriteria = CriteriaTransformer.TransformToRowCount(crit);
3.添加一般查询条件参数
ICriteria c = session.CreateCriteria(typeof(Student)); c.Add(Expression.Eq("StudentNumber", (long)232));
4.添加sql查询条件(?为参数)
ICriteria c = session.CreateCriteria(typeof(Student)); c.Add(Expression.Sql("2 = ?", 1, NHibernateUtil.Int32));
5.别名
ICriteria c = s.CreateCriteria(typeof(Animal), "a").AddOrder(Order.Asc("a.bodyWeight"));
6.分页
session.CreateCriteria<Student>().SetFirstResult(1).SetMaxResults(2)
简单写写就好