`
adaqian
  • 浏览: 30218 次
  • 性别: Icon_minigender_2
  • 来自: 长沙
社区版块
存档分类
最新评论

Hibernate分页查询

阅读更多
package com.ada.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;

import com.ada.bean.Page;


public class MyDAOSupport {
	
	/** 分页查询方法
	 * ada 2010-6-28
	 * @param cri:查询条件对象
	 * @param page:分页对象
	 * @return page:分页对象
	 */
	protected Page getQueryPage(Criteria cri,Page page){
			
		int count = ((Long)cri.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		cri.setProjection(null);
		page.setSumcount(count);//总记录数 
		int pagenum=count/page.getPagesize();
		if(count%page.getPagesize()!=0)
			pagenum+=1;
		page.setPagecount(pagenum);//总页数
		int startNo=(page.getCurpage()-1)*page.getPagesize();
		int endNo=startNo+page.getPagesize();

		cri.setFirstResult(startNo);
		cri.setMaxResults(endNo);
	
		page.setResult(cri.list());
		return page;

	}
}



调用例子:
package com.ada.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;

import com.ada.bean.Page;
import com.ada.bean.User;
import com.ada.dao.UserDAO;
import com.ada.util.HibernateUtil;

public class UserDAOImpl extends MyDAOSupport implements UserDAO {

	public Page queryUserPages(Page page) {
		
		Session s=null;
		try{
			s=HibernateUtil.getSession();
			Criteria cri = s.createCriteria(User.class);
			return getQueryPage(cri,page);
		}finally{
			if(s!=null)
				s.close();
		}
	}

         public Page queryUserPagesByDeptid(String deptid,Page page){
		Session s=null;
		try{
			s=HibernateUtil.getSession();
			Criteria cri = s.createCriteria(User.class);
			cri.add(Restrictions.eq("deptid",Long.valueOf(deptid)));
			return getQueryPage(cri,page);
		}finally{
			if(s!=null)
				s.close();
		}
	}


}



分页对象
package com.ada.bean;

import java.util.List;

public class Page {
	private int pagesize;//每页显示个数
	private int curpage;//当前页
	private int pagecount;//总页数
	private int sumcount;//总记录数
	private List result;

	public int getSumcount() {
		return sumcount;
	}
	public void setSumcount(int sumcount) {
		this.sumcount = sumcount;
	}
	public int getPagecount() {
		return pagecount;
	}
	public void setPagecount(int pagecount) {
		this.pagecount = pagecount;
	}
	public int getCurpage() {
		return curpage;
	}
	public void setCurpage(int curpage) {
		this.curpage = curpage;
	}
	
	public int getPagesize() {
		return pagesize;
	}
	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}
	public List getResult() {
		return result;
	}
	public void setResult(List result) {
		this.result = result;
	}

}



注:
可结合struts2自定义分页标签做前台展示
http://adaqian.iteye.com/blog/707539
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics