参考:https://www.cnblogs.com/ltspring/p/11738178.html

    自己写的代码

    1. 封装实体 ```java @Data public class PageVo {

      private Integer total; //总记录数 private List list; //结果集 private Integer pageNum; // 第几页 private Integer pageSize; // 每页记录数 private Integer pages; // 总页数

    }

    1. 2. 工具类
    2. ```java
    3. /**
    4. * @创建人 jiangchun
    5. * @创建时间 2019/10/23
    6. * @描述
    7. */
    8. @Slf4j
    9. @Component
    10. public class PageUtil {
    11. @Resource
    12. private JdbcTemplate jdbcTemplate;
    13. public PageVo queryForPage(String sql, Integer pageNum, Integer pageSize, Object[] params, RowMapper rowMapper) throws DataAccessException {
    14. if (pageNum == null || pageSize == null) {
    15. return null;
    16. }
    17. if (pageNum < 1) {
    18. pageNum = 1;
    19. }
    20. if (pageSize < 1) {
    21. pageSize = 10;
    22. }
    23. PageVo result = new PageVo();
    24. //获取记录条数
    25. String countSql = "select count(1) as count from (" + sql + ") temp";
    26. log.info("countSql {}", countSql);
    27. List countList = jdbcTemplate.queryForList(countSql, params, Integer.class);
    28. result.setTotal((Integer) countList.get(0));
    29. result.setPageNum(pageNum);
    30. result.setPageSize(pageSize);
    31. int pageCount = result.getTotal() % result.getPageSize();
    32. result.setPages(pageCount == 0 ? (result.getTotal() / result.getPageSize()) : (result.getTotal() / result.getPageSize() + 1));
    33. sql += parseLimit(result);
    34. log.info("queryLimitSql {}", sql);
    35. List data = jdbcTemplate.query(sql, params, rowMapper);
    36. result.setList(data);
    37. return result;
    38. }
    39. private String parseLimit(PageVo pagination) {
    40. StringBuffer stringBuffer = new StringBuffer();
    41. stringBuffer.append(" limit ");
    42. stringBuffer.append(pagination.getPageSize());
    43. stringBuffer.append(" offset ");
    44. stringBuffer.append(pagination.getPageSize()*(pagination.getPageNum()-1));
    45. return stringBuffer.toString();
    46. }
    47. }
    1. dao层

    image.png

    1. public PageStudentVo getList(Student student, Integer pageNum,Integer pageSize) {
    2. List<Object> params = new ArrayList<Object>();
    3. String sql = "select * from student where 1=1 ";
    4. if (student.getRealName() != null && !student.getRealName().trim().equals("")) {
    5. sql += " and realName like CONCAT('%',?,'%')";
    6. params.add(student.getRealName());
    7. }
    8. if (student.getPhone() != null && !student.getPhone().trim().equals("")) {
    9. sql += " and phone = ?";
    10. params.add(student.getPhone());
    11. }
    12. sql += " order by id desc";
    13. System.out.println(sql);
    14. PageStudentVo res = pageUtil.queryForPage(sql, pageNum, pageSize, params.toArray(), new BeanPropertyRowMapper<>(Student.class));
    15. return res;
    16. }