在项目中,分页是经常要用到的,详细记录Hibernate分页技术:
1.借用robbin的代码,稍做修改
AbstractManager.javapackage com.wygl.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.wygl.service.*; public abstract class AbstractManager extends HibernateDaoSupport { private boolean cacheQueries = false; private String queryCacheRegion; public void setCacheQueries(boolean cacheQueries) { this.cacheQueries = cacheQueries; } public void setQueryCacheRegion(String queryCacheRegion) { this.queryCacheRegion = queryCacheRegion; } public void save(final Object entity) { getHibernateTemplate().save(entity); } public void persist(final Object entity) { getHibernateTemplate().save(entity); } public void update(final Object entity) { getHibernateTemplate().update(entity); } public void delete(final Object entity) { getHibernateTemplate().delete(entity); } @SuppressWarnings("unchecked") public Object load(final Class entity, final Serializable id) { return getHibernateTemplate().load(entity, id); } @SuppressWarnings("unchecked") public Object get(final Class entity, final Serializable id) { return getHibernateTemplate().get(entity, id); } @SuppressWarnings("unchecked") public List findAll(final Class entity) { return getHibernateTemplate().find("from " + entity.getName()); } @SuppressWarnings("unchecked") public List findByNamedQuery(final String namedQuery) { return getHibernateTemplate().findByNamedQuery(namedQuery); } @SuppressWarnings("unchecked") public List findByNamedQuery(final String query, final Object parameter) { return getHibernateTemplate().findByNamedQuery(query, parameter); } @SuppressWarnings("unchecked") public List findByNamedQuery(final String query, final Object[] parameters) { return getHibernateTemplate().findByNamedQuery(query, parameters); } @SuppressWarnings("unchecked") public List find(final String query) { return getHibernateTemplate().find(query); } @SuppressWarnings("unchecked") public List find(final String query, final Object parameter) { return getHibernateTemplate().find(query, parameter); } public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria) { return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, 0); } public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int startIndex) { return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, startIndex); } @SuppressWarnings("unchecked") public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int pageSize, final int startIndex) { return (PaginationSupport) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = detachedCriteria.getExecutableCriteria(session); int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue(); criteria.setProjection(null); List items = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list(); PaginationSupport ps = new PaginationSupport(items, totalCount, pageSize, startIndex); return ps; } }, true); } @SuppressWarnings("unchecked") public List findAllByCriteria(final DetachedCriteria detachedCriteria) { return (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = detachedCriteria.getExecutableCriteria(session); return criteria.list(); } }, true); } public int getCountByCriteria(final DetachedCriteria detachedCriteria) { Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = detachedCriteria.getExecutableCriteria(session); return criteria.setProjection(Projections.rowCount()).uniqueResult(); } }, true); return count.intValue(); } }
PaginationSupport.java
package com.wygl.service; import java.util.List; public class PaginationSupport { //每页数量 public final static int PAGESIZE = 30; private int pageSize = PAGESIZE; //查出的记录 @SuppressWarnings("unchecked") private List items; //记录总数 private int totalCount; private int[] indexes = new int[0]; //开始索引号 private int startIndex = 0; //当前页数 private int page = 0; public void setPage(int page){ this.page = page; } public int getPage(){ return startIndex / pageSize + 1; } //总页数 private int totalPage = 0; public void setTotalPage(int totalPage){ this.totalPage = totalPage; } public int getTotalPage(){ int count = totalCount / pageSize; if (totalCount % pageSize > 0) count++; return count; } @SuppressWarnings("unchecked") public PaginationSupport(List items, int totalCount) { setPageSize(PAGESIZE); setTotalCount(totalCount); setItems(items); setStartIndex(0); } @SuppressWarnings("unchecked") public PaginationSupport(List items, int totalCount, int startIndex) { setPageSize(PAGESIZE); setTotalCount(totalCount); setItems(items); setStartIndex(startIndex); } @SuppressWarnings("unchecked") public PaginationSupport(List items, int totalCount, int pageSize, int startIndex) { setPageSize(pageSize); setTotalCount(totalCount); setItems(items); setStartIndex(startIndex); } @SuppressWarnings("unchecked") public List getItems() { return items; } @SuppressWarnings("unchecked") public void setItems(List items) { this.items = items; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { if (totalCount > 0) { this.totalCount = totalCount; int count = totalCount / pageSize; if (totalCount % pageSize > 0) count++; indexes = new int[count]; for (int i = 0; i < count; i++) { indexes[i] = pageSize * i; } } else { this.totalCount = 0; } } public int[] getIndexes() { return indexes; } public void setIndexes(int[] indexes) { this.indexes = indexes; } public int getStartIndex() { return startIndex; } public void setStartIndex(int startIndex) { if (totalCount <= 0) this.startIndex = 0; else if (startIndex >= totalCount) this.startIndex = indexes[indexes.length - 1]; else if (startIndex < 0) this.startIndex = 0; else { this.startIndex = indexes[startIndex / pageSize]; } } public int getNextIndex() { int nextIndex = getStartIndex() + pageSize; if (nextIndex >= totalCount) return -1; else return nextIndex; } public int getPreviousIndex() { int previousIndex = getStartIndex() - pageSize; if (previousIndex < 0) return -1; else return previousIndex; } }
写好2个类后,下来就是应用
2. Action中这样
UserManagerAction.java
/** * DD注释: 显示所有用户 * 分页显示! * @param mapping * @param form * @param request * @param response * @return */ public ActionForward doShowUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ int startIndex; //每页开始索引号 int pageSize = 1; //每页记录数 //获取要访问的页数,第一次访问第一页 String strPage = request.getParameter("page"); if(strPage==""||strPage==null){ startIndex = 0; }else{ startIndex = Integer.parseInt(strPage); } //查找并返回PaginationSupport类型ps,将ps抛到web层 PaginationSupport ps = userService.findUser(pageSize,startIndex); request.setAttribute("ps", ps); System.out.println("2"); return mapping.findForward("showUser"); }
UserService.java
/** * 查找所有用户,分页! * @param pageSize 每页记录数 * @param startIndex 开始索引号 * @return */ public PaginationSupport findUser(int pageSize,int startIndex){ //构造DetachedCriteria动态查询条件 DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class); return userDAO.findPageByCriteria(detachedCriteria, pageSize, startIndex); }
3. 在页面这样应用
showUser.jsp
<c:if test="${ps.page-1 !=0 }"> <a href="userManager.do?command=showUser&page=0">首页</a> </c:if> <c:if test="${ps.previousIndex != -1 }"> <a href="userManager.do?command=showUser&page=${ps.previousIndex }">上一页</a> </c:if> 共查到${ps.totalCount }个用户,共${ps.totalPage }页 第${ps.page }页 <c:if test="${ps.nextIndex != -1}"> <a href="userManager.do?command=showUser&page=${ps.nextIndex }">下一页</a> </c:if> <c:if test="${ps.page != ps.totalPage }"> <a href="userManager.do?command=showUser&page=${ps.totalPage -1 }">末页</a> </c:if>