Java分页查询操作的两种实现办法 下载本文

内容发布更新时间 : 2024/12/26 14:11:44星期一 下面是文章的全部内容请认真阅读。

Dao实现类 public Listpage(int start, int end) { String pagesql = \* from (select id,name,price,descri,rownumrn from t_product)where rn between ? and ?\; List list = newArrayList(); Product p = null; Connection conn = null; PreparedStatementstm = null; ResultSetrs = null; try { conn = JDBCUtil.getConnection(); stm = conn.prepareStatement(pagesql); stm.setInt(1, start); stm.setInt(2, end); rs = stm.executeQuery(); while (rs.next()) { p = new Product(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4)); list.add(p); } } catch (Exception e) {

}

thrownewRuntimeException(\查询page全部异常\, e); } finally { JDBCUtil.close(rs, stm, null); }

return list;

public Long count() { Connection conn = null; PreparedStatementstm = null; ResultSetrs = null; Long count = null; try { conn = JDBCUtil.getConnection(); stm = conn.prepareStatement(\); rs = stm.executeQuery(); while (rs.next()) { count = rs.getLong(1); } } catch (Exception e) { }

thrownewRuntimeException(\查询count\, e); } finally { JDBCUtil.close(rs, stm, null); }

return count;

Service实现类

publicPageBeanqueryPage(intpageNum, intpageSize) { }

int start = (pageNum - 1) * pageSize + 1; int end = pageNum * pageSize;

ProductDaodao = newProductDaoImpl();

List page = dao.page(start, end); Long sum = dao.count();

PageBeanpageBean = newPageBean(); pageBean.setCount(sum); pageBean.setList(page);

pageBean.setPageNum(pageNum); pageBean.setPageSize(pageSize); returnpageBean;

Entity实体类

publicclassPageBean { private Integer pageNum; private Integer pageSize; private Long count; private Listlist; publicPageBean() { } publicPageBean(Integer pageNum, Integer pageSize, Long count, List list) { this.pageNum = pageNum; this.pageSize = pageSize; this.count = count; this.list = list; } public Integer getPageNum() { returnpageNum; } publicvoidsetPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { returnpageSize; } publicvoidsetPageSize(Integer pageSize) { this.pageSize = pageSize; }

}

public Long getCount() { returncount; }

publicvoidsetCount(Long count) { this.count = count; }

public ListgetList() { returnlist; }

publicvoidsetList(List list) { this.list = list; }

Action实现类

privatePageBeanpageBean; publicPageBeangetPageBean() { returnpageBean; } publicvoidsetPageBean(PageBeanpageBean) { this.pageBean = pageBean; }

public ListgetProducts() { returnproducts; } publicvoidsetProducts(List products) { this.products = products; } private Listproducts; public String queryAll() { ProductService service = newProductServiceImpl(); try {

// List list = service.queryAllProduct(); PageBean list = service.queryPage(1, 10); pageBean = list; setProducts(list.getList()); // ServletActionContext.getRequest().setAttribute(\list); // session.put(\ return\; } catch (Exception e) { // TODO Auto-generated catch block

}

session.put(\, \查询全部出错\); return\;