参考:https://www.cnblogs.com/ltspring/p/11738178.html
自己写的代码
封装实体 ```java @Data public class PageVo
{ private Integer total; //总记录数 private List
list; //结果集 private Integer pageNum; // 第几页 private Integer pageSize; // 每页记录数 private Integer pages; // 总页数
}
2. 工具类
```java
/**
* @创建人 jiangchun
* @创建时间 2019/10/23
* @描述
*/
@Slf4j
@Component
public class PageUtil {
@Resource
private JdbcTemplate jdbcTemplate;
public PageVo queryForPage(String sql, Integer pageNum, Integer pageSize, Object[] params, RowMapper rowMapper) throws DataAccessException {
if (pageNum == null || pageSize == null) {
return null;
}
if (pageNum < 1) {
pageNum = 1;
}
if (pageSize < 1) {
pageSize = 10;
}
PageVo result = new PageVo();
//获取记录条数
String countSql = "select count(1) as count from (" + sql + ") temp";
log.info("countSql {}", countSql);
List countList = jdbcTemplate.queryForList(countSql, params, Integer.class);
result.setTotal((Integer) countList.get(0));
result.setPageNum(pageNum);
result.setPageSize(pageSize);
int pageCount = result.getTotal() % result.getPageSize();
result.setPages(pageCount == 0 ? (result.getTotal() / result.getPageSize()) : (result.getTotal() / result.getPageSize() + 1));
sql += parseLimit(result);
log.info("queryLimitSql {}", sql);
List data = jdbcTemplate.query(sql, params, rowMapper);
result.setList(data);
return result;
}
private String parseLimit(PageVo pagination) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(" limit ");
stringBuffer.append(pagination.getPageSize());
stringBuffer.append(" offset ");
stringBuffer.append(pagination.getPageSize()*(pagination.getPageNum()-1));
return stringBuffer.toString();
}
}
- dao层
public PageStudentVo getList(Student student, Integer pageNum,Integer pageSize) {
List<Object> params = new ArrayList<Object>();
String sql = "select * from student where 1=1 ";
if (student.getRealName() != null && !student.getRealName().trim().equals("")) {
sql += " and realName like CONCAT('%',?,'%')";
params.add(student.getRealName());
}
if (student.getPhone() != null && !student.getPhone().trim().equals("")) {
sql += " and phone = ?";
params.add(student.getPhone());
}
sql += " order by id desc";
System.out.println(sql);
PageStudentVo res = pageUtil.queryForPage(sql, pageNum, pageSize, params.toArray(), new BeanPropertyRowMapper<>(Student.class));
return res;
}