日期:2014-05-16  浏览次数:20424 次

Spring jdbctemplate + mysql 分页封装

这里封装的是MYSQL的分页实现,不同数据库的特性不同,如mysql的limit,orcale的rownum,mssql的top

demo架构是:spring(jdbcTemplate) + struts2 + mysql + dbcp

?

分页模型代码:

?

package com.test.util;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

public class Pagination {
	
	public static final int NUMBERS_PER_PAGE = 10;
	private int totalPages;	// 总页数
	private int page;	// 当前页码
	private List resultList;	// 结果集存放List

	public Pagination(String sql, int currentPage, int numPerPage,JdbcTemplate jTemplate) {
		if (jTemplate == null) {
			throw new IllegalArgumentException(
					"com.starhub.sms.util.Pagination.jTemplate is null,please initial it first. ");
		} else if (sql == null || sql.equals("")) {
			throw new IllegalArgumentException(
					"com.starhub.sms.util.Pagination.sql is empty,please initial it first. ");
		}
		
		String countSQL = getSQLCount(sql);
		setPage(currentPage);
		setTotalPages(numPerPage,jTemplate.queryForInt(countSQL));
		int startIndex = (currentPage - 1) * numPerPage;	//数据读取起始index
		
		StringBuffer paginationSQL = new StringBuffer(" ");
		paginationSQL.append(sql);
		paginationSQL.append(" limit "+ startIndex+","+numPerPage);
		setResultList(jTemplate.queryForList(paginationSQL.toString()));
	}
	
	public String getSQLCount(String sql){
		String sqlBak = sql.toLowerCase();
		String searchValue = " from ";
		String sqlCount = "select count(*) from "+ sql.substring(sqlBak.indexOf(searchValue)+searchValue.length(), sqlBak.length());
		return sqlCount;
	}
	
	public int getTotalPages() {
		return totalPages;
	}
	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public List getResultList() {
		return resultList;
	}
	public void setResultList(List resultList) {
		this.resultList = resultList;
	}
	// 计算总页数
	public void setTotalPages(int numPerPage,int totalRows) {
		if (totalRows % numPerPage == 0) {
			this.totalPages = totalRows / numPerPage;
		} else {
			this.totalPages = (totalRows / numPerPage) + 1;
		}
	}

}
?

?

下载DEMO:

1 楼 osacar 2011-07-29  

我自己在你基础上又加了点东西。
很好用的呀,谢谢你啊
2 楼 521069108 2011-09-21  
挺不错的,我也来用用。