分页功能源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Criteria criteria = session.createCriteria(TUser.class);
criteria.add(Expression.eq("age", "20"));
//从检索结果中获取第100条记录开始的20条记录
criteria.setFirstResult(100);
criteria.setFetchSize(20);
通过Query.setFirstResult和Query.setMaxResults方法也可以设定分页范围,如:
Query query = session.createQuery("from TUser");
query.setFirstResult(100);
query.setMaxResults(20); // query.setFetchSize(20);
List list = query.list();
Hibernate中,抽象类org.hibernate.dialect.Dialect指定了所有底层数据库的对外统一接口,通过针对不同数据库提供相应的Dialect实现,数据库之间的差异性得以消除,从而为上层机制提供了透明的、数据库无关的存储层基础。对于分页机制而言,Dialect中定义了一个方法如下:
/**
* Add a LIMIT clause to the given SQL SELECT
*
* @return the modified SQL
*/
public String getLimitString(String querySelect, boolean hasOffset) {
throw new UnsupportedOperationException( "paged queries not supported" );
}
public String getLimitString(String querySelect, int offset, int limit) {
return getLimitString( querySelect, offset>0 );
}
此方法用于在现有Select语句基础上,根据各个数据库自身特性,构造对应的记录返回限定子句。如MySQL中对应的记录限定子句为Limit,Oracle中,通过rownum子句实现。MySQLDialect中的getLimitString实现:
public String getLimitString(String sql, boolean hasOffset) {
return new StringBuffer( sql.length()+20 )
.append(sql)
.append( hasOffset ? " limit ?, ?" : " limit ?")
.toString();
}
MySQLDialect.getLimitString方法的实现实际上是在给定的Select语句后追加MySQL所提供的专有SQL子句limit来实现。
Oracle9Dialect中的getLimitString实现:
public String getLimitString(String sql, boolean hasOffset) {
sqlsql = sql.trim();
boolean isForUpdate = false;
if ( sql.toLowerCase().endsWith(" for update") ) {
sqlsql = sql.substring( 0, sql.length()-11 );
isForUpdate = true;
}
StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
if (hasOffset) {
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
}
else {
pagingSelect.append("select * from ( ");
}
pagingSelect.append(sql);
if (hasOffset) {
pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
}
else {
pagingSelect.append(" ) where rownum <= ?");
}
if ( isForUpdate ) {
pagingSelect.append( " for update" );
}
return pagingSelect.toString();
}
通过Oracle特有的rownum子句来实现数据部分的读取。SQLServerDialect中的getLimitString实现:
public String getLimitString(String querySelect, int offset, int limit) {
if ( offset > 0 ) {
throw new UnsupportedOperationException( "sql server has no offset" );
}
return new StringBuffer( querySelect.length()+8 )
.append(querySelect)
.insert( getAfterSelectInsertPoint(querySelect), " top " + limit )
.toString();
}
通过SQLServer特有的top子句实现。HSQLDialect中的getLimitString实现:
public String getLimitString(String sql, boolean hasOffset) {
return new StringBuffer( sql.length() + 10 )
.append( sql )
.insert( sql.toLowerCase().indexOf( "select" ) + 6, hasOffset ? " limit ? ?" : " top ?" )
.toString();
}
public class articleVO {
private int a_id;
private int a_sort;
private int a_hit;
private int c_id;
private String a_title;
private String a_body;
private String a_author;
private String a_date;
// getter setter
新建page.java
package page.dal;
public class page {
private int totalRows; //总行数
private int pageSize = 10; //每页显示的行数
private int currentPage; //当前页号
private int totalPages; //总页数
private int startRow; //当前页在数据库中的起始行
public page(int _totalRows) {
totalRows = _totalRows;
totalPages=totalRows/pageSize;
int mod=totalRows%pageSize;
if(mod>0){
totalPages++;
}
currentPage = 1;
startRow = 0;
}
public int getStartRow() {
return startRow;
}
public int getTotalPages() {
return totalPages;
}
public int getCurrentPage() {
return currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRows() {
return totalRows;
}
public void first() {
currentPage = 1;
startRow = 0;
}
public void previous() {
if (currentPage == 1) {
return;
}
currentPage--;
startRow = (currentPage - 1) * pageSize;
}
public void next() {
if (currentPage < totalPages) {
currentPage++;
}
startRow = (currentPage - 1) * pageSize;
}
public void last() {
currentPage = totalPages;
startRow = (currentPage - 1) * pageSize;
}
public void refresh(int _currentPage) {
currentPage = _currentPage;
if (currentPage > totalPages) {
last();
}
}
}
新建 pageHelp.java
package page.dal;
import javax.servlet.http.*;
public class PagerHelp {
public static page getPager(HttpSer
vletRequest httpServletRequest,int totalRows) {
//定义pager对象,用于传到页面
page pager = new page(totalRows);
//从Request对象中获取当前页号
String currentPage = httpServletRequest.getParameter("currentPage");
//如果当前页号为空,表示为首次查询该页
//如果不为空,则刷新page对象,输入当前页号等信息
if (currentPage != null) {
pager.refresh(Integer.parseInt(currentPage));
}
//获取当前执行的方法,首页,前一页,后一页,尾页。
String pagerMethod = httpServletRequest.getParameter("pageMethod");
if (pagerMethod != null) {
if (pagerMethod.equals("first")) {
pager.first();
} else if (pagerMethod.equals("previous")) {
pager.previous();
} else if (pagerMethod.equals("next")) {
pager.next();
} else if (pagerMethod.equals("last")) {
st();
}
}
return pager;
}
}
新建 util.java
package page.dal;
import net.sf.hibernate.Query;
import net.sf.hibernate.cfg.Configuration;
import java.util.List;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Session;
import java.util.*;
public class util {
public util() {
}
private Session ss=null;
public Session getSession()
{
// Configuration config=null;
SessionFactory sessionFactory;
try {
Configuration cfg = new Configuration();
sessionFactory = cfg.addClass(articleVO.class).
buildSessionFactory();
// SessionFactory sessionFactory=config.buildSessionFactory();
ss = sessionFactory.openSession();
return ss;
} catch (HibernateException ex) {
System.out.print("getsession出错了。。" + ex.getMessage());
return null;
}
}
public int getCount()
{
String sql="select count(*) from articleVO" ;
this.getSession();
try {
// ss.createQuery("select count(a)as cont from articleVO a ");
int rows= ((Integer) ss.iterate(sql).next()).intValue();
ss.flush();
return rows;
} catch (HibernateException ex) {
System.out.print("ex::"+ex.getMessage());
return 0;
}
}
public Collection getList(int pagesize,int currow) throws HibernateException {
Collection vehicleList = null;
this.getSession();
Query q=ss.createQuery("from articleVO");
q.setFirstResult(currow);
q.setMaxResults(pagesize);
vehicleList=q.list();
ss.flush();
return vehicleList;
}
}
新建 struts PageAction.java
package page.dal;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRespon
se;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import page.dal.*;
import java.util.*;
import net.sf.hibernate.*;
public class pageAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
Collection clInfos = null;//用于输出到页面的记录集合
int totalRows;//记录总行数
util dal=new util();
totalRows=dal.getCount();
System.out.print("总行数=="+totalRows);
page p=PagerHelp.getPager(request,totalRows);
try {
clInfos = dal.getList(p.getPageSize(), p.getStartRow());
} catch (HibernateException ex) {
System.out.print("action里的错误="+ex.getMessage());
}
request.setAttribute("page",p);
request.setAttribute("list",clInfos);
return mapping.findForward("page");
//pageForm pageForm = (pageForm) form;
// throw new ng.UnsupportedOperationException(
// "Method $execute() not yet implemented.");
}
}
前台页面
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ page contentType="text/html; charset=GBK" %>
pagea_title a_body a_a_date a_author
第
共