今天做项目的时候,要实现分页查询的功能,一开始的想法就是用SQL语句实现(项目数据操作是用Nhibernate),但认真考虑了下发现在所做的项目里实现会很麻烦,果断放弃了用SQL语句。因为刚接触NHibernate时间不长,对Nhibernate认识不深,但在做项目的这段时间里接触它,发现Nhibernate真的很好用(以前怎么就没有去了解它呢)。

     在Nhibernate里实现分页很简单,用 SetFirstResult 和SetMaxResults就可以实现,SetFirstResult 简单的理解就是从第几条记录开始,SetMaxResults是取几条记录。以下是一个测试的代码,从Customer表里取记录,主要的就是GetCustomerListTest方法:

 

代码
public partial class Default : System.Web.UI.Page
{
private ISession _session;
private SessionManager _helper;
private NHibernateSample _sample;
protected void Page_Load(object sender, EventArgs e)
{
_helper
= new SessionManager();
_session
= _helper.GetSession();
_sample
= new NHibernateSample(_session);
}
protected void btnClick_Click(object sender, EventArgs e)
{
IList
<Customer> customerList = GetCustomerListTest(5, 10, "select *from Customer");
int i=0;
string[] nameArrary = new string[customerList.Count];
foreach (Customer customer in customerList)
{
nameArrary[i]
= customer.FirstName + customer.LastName;
i
++;
}
foreach (var name in nameArrary)
{
Response.Write(name
+ "<br />");
}
}
/// <summary>
/// 分页测试
/// </summary>
/// <param name="pageStart">开始查找的记录条</param>
/// <param name="pageLimit">显示数量</param>
/// <param name="sql"></param>
/// <returns></returns>
public IList<Customer> GetCustomerListTest(int pageStart, int pageLimit, string sql)
{
IList
<Customer> customerList = _session.CreateSQLQuery(sql)
.SetFirstResult(pageStart)
.SetMaxResults(pageLimit)
.SetResultTransformer(Transformers.AliasToBean
<Customer>()).List<Customer>();
return customerList;
}

 

 posted on 2010-12-04 08:54  john chen  阅读(4454)  评论(7编辑  收藏  举报