hibernate分页的实现

来源:互联网 发布:英文表达祝福知乎 编辑:程序博客网 时间:2024/05/16 15:03

系统采用springMVC+hibernate架构,本文是基于网络上的一个paginationsupport类经过修改而成,下面直接贴代码:

1.PaginationSupport类(封装页面数据)

package com.darren.demo3l.commonUtils;import java.util.List;public class PaginationSupport { public final static int PAGESIZE = 5;//设置每页显示记录的多少 private int pageSize = PAGESIZE;//总记录条数  private int totalCount;//当前页 private int currentPage;//当前页起始记录索引 private int startIndex;//保存每一页的第一条记录的索引 private int[] indexes = new int[0];//下一页第一条记录索引  private int nextIndex;//上一页第一条记录索引  private int previousIndex;//总页数  private int pageCount;//返回查询结果 private List items;//最后一页第一条记录的索引  private int lastIndex;  public  PaginationSupport(int pageSize,int startIndex) {  setPageSize(pageSize);  setStartIndex(startIndex);   } public  PaginationSupport(List items, int totalCount) {  setPageSize(PAGESIZE);  setTotalCount(totalCount);  setItems(items);  setStartIndex(0);  } public  PaginationSupport(List items, int totalCount, int startIndex) {  setPageSize(PAGESIZE);  setTotalCount(totalCount);  setItems(items);  setStartIndex(startIndex);   } public  PaginationSupport(List items, int totalCount, int pageSize,   int startIndex) {  setPageSize(pageSize);  setTotalCount(totalCount);  setItems(items);  setStartIndex(startIndex);   }//设置总记录数 public void setTotalCount(int totalCount) {  if (totalCount > 0) {   this.totalCount = totalCount;   int count = totalCount / pageSize;   if (totalCount % pageSize > 0){    count++;//count计算的是总页数   }   indexes = new int[count];   for (int i = 0; i < count; i++) {    indexes[i] = pageSize * i;//indexes[i]存取了每i+1页的第一条记录的索引   }    }  else {   this.totalCount = 0;  } } //获取记录总数 public int getTotalCount() {  return totalCount; } //设置每一页第一条记录的索引 public void setIndexes(int[] indexes) {  this.indexes = indexes; }//返回每一页第一条记录的索引 public int[] getIndexes() {  return indexes; }      //设置起始记录索引 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 getStartIndex() {  return startIndex; } //设置下一页索引 public void setNextIndex(int nextIndex) {  this.nextIndex = nextIndex; }  //获取下一页首条记录的索引 public int getNextIndex() {  int nextIndex = getStartIndex() + pageSize;  if (nextIndex >= totalCount)   return getStartIndex();  else   return nextIndex; } // 设置上一页的起始记录索引 public void setPreviousIndex(int previousIndex) {  this.previousIndex = previousIndex; }    // 获取上一页的起始记录索引 public int getPreviousIndex() {  int previousIndex = getStartIndex() - pageSize;  if (previousIndex < 0)   return 0;  else   return previousIndex; }    // 获取上一页的起始记录索引 public void setPageCount(int pageCount) {  this.pageCount = pageCount; }    //获取总页数  public int getPageCount() {  int count = totalCount / pageSize;  if (totalCount % pageSize > 0)   count++;  return count; } //获取当前页 public int getCurrentPage() {  return getStartIndex() / pageSize + 1; }  //设置当前页 public void setCurrentPage(int currentPage) {  this.currentPage = currentPage; } //设置最后一页的首条记录的索引 public void setLastIndex(int lastIndex) {  this.lastIndex =lastIndex ; } //获取最后一页的首条记录的索引 public int getLastIndex() {  return indexes[indexes.length-1]; } //获取当前页的每页条数 public int getPageSize() {  return pageSize; }//设置每页条数 public void setPageSize(int pageSize) {  this.pageSize = pageSize; }//获取返回记录 public List getItems() {  return items; }    //设置返回记录 public void setItems(List items) {  this.items = items; }}
2.dao层查询分页数据的方法

@SuppressWarnings("unchecked")public PaginationSupport findPageByCriteria( final  String hsql,  final int pageSize,final int startIndex) { System.out.println("进入查询"); PaginationSupport paginationSupport = null; try { paginationSupport=getHibernateTemplate().execute(new HibernateCallback(){ //调用hibernate的条件查询;@Overridepublic Object doInHibernate(Session session)throws HibernateException, SQLException{Query query  =  session.createQuery(hsql);            int totalCount=query.list().size();            query.setFirstResult(startIndex);             query.setMaxResults(pageSize);             List items  = query.list();            PaginationSupport ps = new PaginationSupport(items,            totalCount, pageSize, startIndex);            return ps;}  });} catch (Exception e) {e.printStackTrace();} return paginationSupport;}


3.分页查询的公共显示页面。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %><c:set var="ctx" value="${pageContext.request.contextPath }"/> <script type="text/javascript" src="${ctx}/resources/js/common/jquery-1.7.1.js"></script> <script type="text/javascript" src="${ctx}/resources/js/common/jquery.validate.js"></script> <script type="text/javascript"> /** * @author IRun */ //跳转到指定页面  function topage(obj){  window.location.href="${ctx}/user/getperson.do?page="+obj;  }    //跳转到任意页面  function torandpage(){  var page=$("#pageInput").val();  if(page==""){  return false;  }    else{  var patrn=/^([1-9]\d*|0)(\.\d*[1-9])?$/;   if (!patrn.exec(page)) {  alert("输入页码不合法");  return false;  }  else{  var pagecount=$("#pagecount").val();  if(page>pagecount)  page=pagecount;  }  if(page<=0){  page=1;  }  window.location.href="${ctx}/user/getperson.do?page="+page;  }    } </script> <div> <input type="hidden" value="${ctx}"  id="context" /><font >    当前页:第${personlist.currentPage}页 | 总记录数:${personlist.totalCount}条 | 每页显示:${personlist.pageSize}条 | 总页数:${personlist.pageCount}页</font>  <c:choose><c:when test="${personlist.currentPage==1}"><b><font color="#ffff00">首页</font></b></c:when><c:otherwise><a href="javascript:topage('1')">首页</a></c:otherwise></c:choose><c:if test="${personlist.currentPage>=2}"><a href="javascript:topage('${personlist.currentPage-1}')">上一页</a></c:if><c:if test="${personlist.currentPage!=1&&personlist.currentPage!=personlist.pageCount}"><b><font color="#000000">第${personlist.currentPage}页</font></b></c:if><c:if test="${personlist.currentPage<personlist.pageCount}"><a href="javascript:topage('${personlist.currentPage+1}')">下一页</a></c:if><c:choose><c:when test="${personlist.currentPage<personlist.pageCount}"><a href="javascript:topage('${personlist.pageCount}')">末页</a></c:when><c:otherwise><b><font color="#FFFF">末页</font></b></c:otherwise></c:choose><span >跳转到:</span><input  type="text" id="pageInput" name="page" value="${personlist.currentPage}" size="4" />页   <input  type="hidden" id="pagecount" name="pages" value="${personlist.pageCount}" size="4" />页 <a  id="goPageBnt" onclick="return torandpage();" href='#'>确定</a></div>
4.数据具体显示页面。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %><c:set var="ctx" value="${pageContext.request.contextPath }"/><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>  <body> <div> <table> <caption><br>显示所有用户</caption> <tr> <td>用户id</td> <td>名称</td><td>性别</td><td>job编号</td></tr> <c:forEach var="persons" items="${personlist.items}"> <tr><td>${persons.personid}</td><td>${persons.personname}</td><td>${persons.sex}</td><td>${persons.job.jobid}</td></tr> </c:forEach>  </table> </div> <div><jsp:include page="/WEB-INF/pages/common/paging.jsp"></jsp:include></div>  </body></html>

5.action 层的方法为接收page参数,然后调用service层的获取分页数据的方法,最后返回PaginationSupport对象,action太简单再次略过,最后贴一下service层调用dao层分页数据的方法:

public PaginationSupport findPage(int page){String hsql="from Person p";int  startIndex=PaginationSupport.PAGESIZE*(page-1);PaginationSupport paginationSupport;paginationSupport=persoDao.findPageByCriteria(hsql, PaginationSupport.PAGESIZE, startIndex);return paginationSupport;}
 

本处贴的代码实现了基本的功能,代码很多不规范,页面也没美化,欢迎吐槽。


原创粉丝点击