Java分页查询操作的两种实现办法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Dao实现类
public List
String pagesql = "select * from (select id,name,price,descri,rownumrn from t_product)where rn between ? and ?";
List
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) {
thrownew RuntimeException("查询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("select count(*) from t_product");
rs = stm.executeQuery();
while (rs.next()) {
count = rs.getLong(1);
}
} catch (Exception e) {
thrownew RuntimeException("查询count", e);
} finally {
JDBCUtil.close(rs, stm, null);
}
return count;
}
Service实现类
public PageBean
int start = (pageNum - 1) * pageSize + 1;
int end = pageNum * pageSize;
ProductDaodao = new ProductDaoImpl();
List
Long sum = dao.count();
PageBean
pageBean.setCount(sum);
pageBean.setList(page);
pageBean.setPageNum(pageNum);
pageBean.setPageSize(pageSize);
return pageBean;
}
Entity实体类
publicclass PageBean
private Integer pageNum;
private Integer pageSize;
private Long count;
private List
public PageBean() {
}
public PageBean(Integer pageNum, Integer pageSize, Long count, List
this.pageNum = pageNum;
this.pageSize = pageSize;
this.count = count;
this.list = list;
}
public Integer getPageNum() {
return pageNum;
}
publicvoid setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
publicvoid setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}