Nhibernate学习笔记(2)

接着来学习条件查询(Criteria Queries)

1、创建ICriteria

NHibernate.ICriteria接口支持特定条件的查询。ISession可以创建ICriteria实例。

ICriteria criteria = session.CreateCriteria(typeof(Person));
criteria.SetMaxResults(
50);
IList<Person> result 
= criteria.List();

2、使用Restrictions添加查询条件

Restrictions是hibernate3代替hibernate2中的Expression,但在hibernate3中Expression还是可以使用的

ICriteria criteria = session.CreateCriteria(typeof(Person));
criteria.Add(Restrictions.Like(
"Firstname""name%"));
criteria.Add(Restrictions.Eq(
"Age"12));
IList
<Person> result = criteria.List<Person>();

3、使用Order排序

使用ICriteria.Order对结果集排序,第二个参数true代表asc,false代表desc。

ICriteria criteria = session.CreateCriteria(typeof(Person));
criteria.AddOrder(
new Order("Firstname"true));
IList
<Person> result = criteria.List<Person>();

4、其他查询

QBE 摘自:NHibernate之旅(4):探索查询之条件查询(Criteria Query)

根据示例查询(Query By Example)

根据示例查询(QBE,Query By Example)是条件查询的一种特殊情况,NHibernate.Criterion.Example类根据你指定的实例创造查询条件。其典型的用法:创建一个Example实例;在Example实例上设置值;根据Example和设置NHibernate返回其对象集合。

例如下面的例子,按照指定Customer查询数据库里的记录:

public IList<Customer> Query()
{
    Customer customerSample = new Customer() { Firstname = "YJing", Lastname = "Lee" };
    return _session.CreateCriteria(typeof(Customer))
        .Add(Example.Create(customerSample))
        .List<Customer>();
}

你可以自行调整Example使之更实用:

public IList<Customer> UseQueryByExample_GetCustomer(Customer customerSample)
{
    Example example = Example.Create(customerSample)
        .IgnoreCase()
        .EnableLike()
        .SetEscapeCharacter('&');
    return _session.CreateCriteria(typeof(Customer))
       .Add(example)
       .List<Customer>();
}
 
还有HQL。暂时不学习~~
 
 
原文地址:https://www.cnblogs.com/xujiaoxiang/p/1723148.html