NHibernate-note

1.http://www.hibernate.org/下载NHibernate最新版本
2.进入http://www.codesmithtools.com/下载工具,编写模板
3.用CodeSmith创建数据库中表的相应对象 .cs文件和.xml文件

 

HQL 不区分大小写:
数组:用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[]>();
}

public IList<Customer> GetCustomersByFirstname(string first
name)
{
//写法1
//return _session.CreateQuery("select from Customer c
where c.Firstname='" + firstname + "'")
// .List<Customer>();
//写法2:位置型参数
//return _session.CreateQuery("select from Customer c
where c.Firstname=?")
// .SetString(0, firstname)
// .List<Customer>();
//写法3:命名型参数(推荐)
return _session.CreateQuery("select from Customer c wh
ere c.Firstname=:fn")
.SetString("fn", firstname)
.List<Customer>();
}
书写HQL 参数有四种写法:
· 写法1:可能会引起SQL 注入,不要使用。
· 写法2:ADO.NET 风格的?参数,NHibernate 的参数从0 开始计数。
· 写法3:命名参数用:name 的形式在查询字符串中表示,这时IQuery 接口把实际
参数绑定到命名参数。
· 写法4:命名的参数列表,把一些参数添加到一个集合列表中的形式,比如可以查
询数据是否在这个集合列表中。


在NHibernate 中使用原生SQL、HQL、Criteria API 三种查询方式来关联查询

下面我们来看看在NHibernate 中使用原生SQL 查询。这篇来完成查询订单在orderDat
a 之后的顾客列表不同查询的写法。
public IList<Customer> UseSQL_GetCustomersWithOrders(Da
teTime orderDate)
{
return _session.CreateSQLQuery("select distinct {custom
er.*} from Customer {customer}"+
" inner join [Order] o on o.Customer={customer}.Custo
merId where o.OrderDate> :orderDate")
.AddEntity("customer", typeof(Customer))
.SetDateTime("orderDate", orderDate)
.List<Customer>();
}


2.HQL关联查询
查询订单在orderData 之后的顾客列表的HQL 关联查询写法:
public IList<Customer> UseHQL_GetCustomersWithOrders(Da
teTime orderDate)
{
return _session.CreateQuery("select distinct c from Custo
mer c ,"
+ "c.Orders.elements o where o.OrderDate > :order
Date")
.SetDateTime("orderDate", orderDate)
.List<Customer>();
}


3.Criteria API关联查询
public IList<Customer> UseCriteriaAPI_GetCustomersWithOrd
ers(DateTime orderDate)
{
return _session.CreateCriteria(typeof(Customer))
.CreateCriteria("Orders")
.Add(Restrictions.Gt("OrderDate", orderDate))
.SetResultTransformer(new NHibernate.Transform.Dist
inctRootEntityResultTransformer())
//或者.SetResultTransformer(NHibernate.CriteriaUtil.Di
stinctRootEntity)
.List<Customer>();
}

posted on 2011-12-30 12:13  cw_volcano  阅读(180)  评论(0编辑  收藏  举报