NHibernate查询语言(HQL,NHibernate Query Language)是NHibernate特有的基于面向对象的SQL查询语言,它具有继承、多态和关联等特性。实际上是用OOP中的对象和属性映射了数据库中的表和列。
其实对照着Linq和SQL原生语句,HQL并不是特别难以理解
以下内容中NHelper.GetCurrentSession都是从Nhelper辅助类中取得ISession
//最基本查询
public static IList<Test> GetAll()
{
ISession session = NHelper.GetCurrentSession();
IQuery iq = session.CreateQuery("from Test");
return iq.List<Test>();
}
这个是最基本查询,查出Test表所有内容,至于用static是为了以后不用实例化它而是直接调用。
//条件查询
public static IList<string> select()
{
return NHelper.GetCurrentSession().CreateQuery("select c.Name from Test c").List<string>();
}
这个是查询表Test中所有Name列内容
//属性查询
public static IList<object[]> selectObject()
{
return NHelper.GetCurrentSession().CreateQuery("select c.Name,count(c.Name) from Test c group by c.Name").List<object[]>();
}
这个是查询表Test中Name列属性,包括Name字段内容数量的统计
//分组查询
public static IList<string> Distinct()
{
return NHelper.GetCurrentSession().CreateQuery("select distinct c.Name from Test c").List<string>();
}
这个是对Test表中Name列进行分组
//where子句
public static IList<Test> where()
{
return NHelper.GetCurrentSession().CreateQuery("from Test c where c.Name=:fn").SetString("fn", "xxx").List<Test>();
}
这个就是条件查询,查询Test中Name列值为XXX的内容
,至于orderby ,groupby内容其实差不多的,用的时候再去看文档吧,特别是最后一个条件查询,setString ,这样的约束特别多,有时间可以慢慢的看一下,还是蛮有意思的。
至于HQL就只能总结这么多了。