日期:2014-05-16 浏览次数:20509 次
最近项目中使用到了JBDCTemplate ,小弟不才,没发现其中包括分页的功能,只好自己做了一个简单的分页功能。下面把心得和源代码分享给大家。
用到了2个类,都是封装好的,如下:
1.page类
用于分页的对象,算是BO了,不只是简单的封装Page的属性,还做了一点点逻辑
/**
*
*/
package com.hipay.bo;
import java.util.ArrayList;
import java.util.List;
/**
* @author TonyDev
*
*/
public class Page {
private int pageCount=1;
private int currentPage=1;
private int pageSize=10;
private int maxPage=1;
private List resultSet=new ArrayList();
public int getCurrentPage() {
checkPage();
return currentPage;
}
private void initMaxPage()
{
this.maxPage = (this.pageCount + this.pageSize - 1) / this.pageSize;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getMaxPage() {
return this.maxPage;
}
public void setMaxPage(int maxPage) {
this.maxPage = maxPage;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
initMaxPage();
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List getResultSet() {
return resultSet;
}
public void setResultSet(List resultSet) {
this.resultSet = resultSet;
}
private void checkPage()
{
if(this.currentPage<1)
this.currentPage=1;
if(this.currentPage>this.maxPage)
this.currentPage=this.maxPage;
}
}
2.PageTemplate
用于分离出ResultSet,并装载Page对象
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlProvider;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
/**
* @author TonyDev
*
*/
public class PageTemplate extends JdbcTemplate {
private Page page = new Page();
public List queryForPage(final String sql, final RowMapper rowMapper)
throws DataAccessException {
Assert.notNull(sql, "SQL must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL query [" + sql + "]");
}
// 重新构造的statementCallback实现
class QueryStatementCallback implements StatementCallback, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
return ResultSetForList(rs, rowMapper);
} finally {
JdbcUtils.closeResultSet(rs);
}
}
public String getSql() {
return sql;
}
}
return (List) execute(new QueryStatementCallback());
}
/**
* 分页之后,填充到以对象形式存储的List 中
*
* @param rs
* 记录集
* @param rm
* 对象转换填充器
* @return List
* @throws SQLException
*/
private List ResultSetForList(ResultSet rs, RowMapper rm) {
List listArray = new ArrayList();