JdbcTemplate 2 中分页查询简介。 一、第一种方法
// sqlFetchRows分页sql语句
// startRow 开始行
// currentRow 当前行
// pageSize页面大小
// 实体类rowMapper
JdbcTemplate.query(sqlFetchRows,args, new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException,
DataAccessException {
final List result = fr.getResult();
int currentRow = 0;
while (rs.next() && currentRow < startRow + pageSize) {
if (currentRow <= startRow) {
result.add(rowMapper.mapRow(rs, currentRow));
}
currentRow++;
}
return result;
}
});
二、第二种方法
String yoursql = "select * from XXX";
StringBuffer sqlQuery = new StringBuffer();
sqlQuery.append("select * from (select temp.*,rownum rownumber from (")
.append(yoursql)
.append("))");
// objects 参数数组Object[]
//总记录数
int totalRows = jdbcTemplate.queryForInt(sqlCount.toString(), objects);
//开始索引位置
int startIndex = (currentPage - 1)*Constant.PAGESIZE;
//最后一条记录的索引位置
int lastIndex = 0;
//总页数
int totalPages = 0;
if (totalRows % PAGESIZE == 0) {
totalPages = totalRows / PAGESIZE;
} else {
totalPages = (totalRows / PAGESIZE) + 1;
}
if (totalRows < PAGESIZE){
lastIndex = totalRows;
} else if ((currentPage == totalPages && totalRows % PAGESIZE == 0) || currentPage < totalPages) {
lastIndex = currentPage*PAGESIZE;
} else if ((currentPage == totalPages && totalRows % PAGESIZE != 0)) {
lastIndex = totalRows;
}
sqlQuery.append(") temp where ROWNUM <= ")
.append(lastIndex)
.append(" ) where rownumber > ")
.append(startIndex);
List list = this.jdbcTemplate.queryForList(sqlQuery.toString(), objects);
// sqlFetchRows分页sql语句
// startRow 开始行
// currentRow 当前行
// pageSize页面大小
// 实体类rowMapper
JdbcTemplate.query(sqlFetchRows,args, new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException,
DataAccessException {
final List result = fr.getResult();
int currentRow = 0;
while (rs.next() && currentRow < startRow + pageSize) {
if (currentRow <= startRow) {
result.add(rowMapper.mapRow(rs, currentRow));
}
currentRow++;
}
return result;
}
});
二、第二种方法
String yoursql = "select * from XXX";
StringBuffer sqlQuery = new StringBuffer();
sqlQuery.append("select * from (select temp.*,rownum rownumber from (")
.append(yoursql)
.append("))");
// objects 参数数组Object[]
//总记录数
int totalRows = jdbcTemplate.queryForInt(sqlCount.toString(), objects);
//开始索引位置
int startIndex = (currentPage - 1)*Constant.PAGESIZE;
//最后一条记录的索引位置
int lastIndex = 0;
//总页数
int totalPages = 0;
if (totalRows % PAGESIZE == 0) {
totalPages = totalRows / PAGESIZE;
} else {
totalPages = (totalRows / PAGESIZE) + 1;
}
if (totalRows < PAGESIZE){
lastIndex = totalRows;
} else if ((currentPage == totalPages && totalRows % PAGESIZE == 0) || currentPage < totalPages) {
lastIndex = currentPage*PAGESIZE;
} else if ((currentPage == totalPages && totalRows % PAGESIZE != 0)) {
lastIndex = totalRows;
}
sqlQuery.append(") temp where ROWNUM <= ")
.append(lastIndex)
.append(" ) where rownumber > ")
.append(startIndex);
List list = this.jdbcTemplate.queryForList(sqlQuery.toString(), objects);