HQL用法小结

1、 Hql不区分大小写,但用到的类、属性名称是区分大小写的。在语句中可以直接使用DB提供的函数,如:..... and DATEPART(hh,Datatime)=0 ,使用了Sql ServerDatePart函数。

 

 

2、 Hql的参数可以用“?”标识,如Where A=? and B=?,赋值时使用参数的索引定位赋值SetString(0,value),也可以使用命名方式,如 Where A=:a,赋值使用SetString("a",value)。不建议使用字符串拼接的方式组装Hql,因为值的内容可能引起Hql语句混乱及SQL注入等问题。

 

3、使用Selected子句

1.简单用法:在结果集中返回指定的对象和属性。

public IList<int> Select()

{

    //返回所有CustomerCustomerId

    return _session.CreateQuery("select c.CustomerId from Customer c")

        .List<int>();

}

 

2.数组:用Object[]的数组返回多个对象和/或多个属性,或者使用特殊的elements功能,注意一般要结合group by使用。

public IList<object[]> SelectObject()

{

   return _session.CreateQuery("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname")

        .List<object[]>();

}或者使用类型安全的.NET对象,以后在实例中说明。

 

3.统计函数:用Object[]的数组返回属性的统计函数的结果,注意统计函数的变量也可以是集合count( elements(c.CustomerId) )

 

public IList<object[]> AggregateFunction()

{

    return _session.CreateQuery("select avg(c.CustomerId),sum(c.CustomerId),count(c) from Customer c")

        .List<object[]>();

}

 

4.Distinct用法:distinctall关键字的用法和语义与SQL相同。实例:获取不同CustomerFirstName

 

public IList<string> Distinct()

{

     return _session.CreateQuery("select distinct c.Firstname from Customer c")

        .List<string>();

}

 

4、可以通过SetMaxResult方法,设定最大返回记录数

posted @ 2008-12-12 09:15  Byeah  阅读(1879)  评论(0编辑  收藏  举报