Springboot中PageHelper 分页查询使用方法(mybatis+thymeleaf)

一:导入依赖

<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper-spring-boot-starter</artifactId>
	<version>1.2.13</version>
</dependency>

二:配置yml文件中PageHelper的属性

pagehelper:                #分页插件
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params:

三:在controller类中使用,

1.在查询方法上调用PageHelper.startPage()方法,设置分页的页数和每页信息数,
2.将查询出来的结果集用PageInfo的构造函数初始化为一个分页结果对象
3.将分页结果对象存入model,返回前端页面
@GetMapping("/types")
public String types(@RequestParam(required = false,defaultValue = "1",value = "pagenum")int pagenum, Model model){

    PageHelper.startPage(pagenum, 5);  //pagenum:页数,pagesize:每页的信息数
    
    List<Type> allType = typeService.getAllType(); //调用业务层查询方法
    
    PageInfo<Type> pageInfo = new PageInfo<>(allType); //得到分页结果对象
    
    model.addAttribute("pageInfo", pageInfo);  //携带分页结果信息
    
    return "admin/types";  //回到前端展示页面
}

四:前端展示分页(thymeleaf+semantic-ui),这里ui用自己的就行,比如bootstrap或layui,主要是thymeleaf的使用。

<table  class="ui compact celled teal table">
  <thead>
  <tr>
    <th></th>
    <th>名称</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>
  <tr th:each="type, iterStat : ${pageInfo.list}">
    <td th:text="${iterStat.count}">1</td>
    <td th:text="${type.name}">摸鱼方法</td>
    <td>
      <a href="#" th:href="@{/admin/types/{id}/input(id=${type.id})}" class="ui mini teal basic button">编辑</a>
      <a href="#" th:href="@{/admin/types/{id}/delete(id=${type.id})}" class="ui mini red basic button">删除</a>
    </td>
  </tr>
  </tbody>
  <tfoot>
  <tr>
    <th colspan="7">
      <div class="ui mini pagination menu"  >
        <div class="item"><a th:href="@{/admin/types}">首页</a></div>
        <div class="item"><a th:href="@{/admin/types(pagenum=${pageInfo.hasPreviousPage}?${pageInfo.prePage}:1)}">上一页</a></div>
        <div class="item"><a th:href="@{/admin/types(pagenum=${pageInfo.hasNextPage}?${pageInfo.nextPage}:${pageInfo.pages})}">下一页</a></div>
        <div class="item"><a th:href="@{/admin/types(pagenum=${pageInfo.pages})}">尾页</a></div>
      </div>
      <a href="#" th:href="@{/admin/types/input}" class="ui mini right floated teal basic button">新增</a>
    </th>
  </tr>
  </tfoot>
</table>

<div class="ui segment m-inline-block">
  <p >当前第<span th:text="${pageInfo.pageNum}"></span>页,总<span th:text="${pageInfo.pages}"></span>页,共<span th:text="${pageInfo.total}"></span>条记录</p>
</div>

五:效果展示(pagesize设置为5的效果)

在这里插入图片描述

发布了35 篇原创文章 · 获赞 26 · 访问量 7154

猜你喜欢

转载自blog.csdn.net/qq_42804736/article/details/104768760