日期:2014-05-16 浏览次数:20604 次
接上篇的实体,DAO接口,实现,测试及XML?http://ponlya.iteye.com/blog/1017538,这里只把上篇中的分页对象贴出来,其中参考了:参考: http://www.codefutures.com/tutorials/spring-pagination/文章
com.spring305.jdbc.page.CurrentPage.java
public class CurrentPage<E> { private int pageNumber; private int pagesAvailable; private List<E> pageItems = new ArrayList<E>(); public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public void setPagesAvailable(int pagesAvailable) { this.pagesAvailable = pagesAvailable; } public void setPageItems(List<E> pageItems) { this.pageItems = pageItems; } public int getPageNumber() { return pageNumber; } public int getPagesAvailable() { return pagesAvailable; } public List<E> getPageItems() { return pageItems; } }
?
分页辅助类com.spring305.jdbc.page.PagingHelper.java
import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; /** * 分页辅助类 * * @author ZhengChao * */ public class PagingHelper<E> { @SuppressWarnings("unchecked") public CurrentPage<E> fetchPage( final JdbcTemplate jt, final String sqlCountRows, final String sqlFetchRows, final Object args[], final int pageNo, final int pageSize, final ParameterizedRowMapper<E> rowMapper) { // determine how many rows are available int rowCount = jt.queryForInt("select count(*) from T_people where id >= ?",new Object[]{1}); rowCount = jt.queryForInt(sqlCountRows, args); // calculate the number of pages int pageCount = rowCount / pageSize; if (rowCount > pageSize * pageCount) { pageCount++; } // create the page object final CurrentPage<E> page = new CurrentPage<E>(); page.setPageNumber(pageNo); page.setPagesAvailable(pageCount); // fetch a single page of results final int startRow = (pageNo - 1) * pageSize; jt.query(sqlFetchRows, args, new ResultSetExtractor() { public Object extractData(ResultSet rs) throws SQLException, DataAccessException { final List pageItems = page.getPageItems(); int currentRow = 0; while (rs.next() && currentRow < startRow + pageSize) { if (currentRow >= startRow) { pageItems.add(rowMapper.mapRow(rs, currentRow)); } currentRow++; } return page; } }); return page; } }
?
测试:
@Test//分页测试 public void testPage() throws SQLException{ CurrentPage<People> currentPagePeople = peopleDao.getPeoplePage(1, 2, 0); List<People> pList = currentPagePeople.getPageItems(); for (int i = 0; i <pList.size(); i++) { System.out.println(pList.get(i)); } }
?