springboot整合Mybatis实现分页

    科技2022-07-21  106

    文章目录

    一、在pom中添加分页插件依赖二、配置application.properties三、编写三层代码1、entity实体类2、Controller控制层3、service、serviceImpl 业务层4、dao、dao.xm数据访问层 四、SQL五、前端界面六、运行结果


    一、在pom中添加分页插件依赖

    代码如下(示例):

    <!--分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-autoconfigure</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>

    二、配置application.properties

    代码如下(示例):

    #设置访问端口 server.port=8081 #thymeleaf配置,这里是可以省略的,因为默认配置已经足够 #关闭缓存,及时刷新页面,这一点很重要 spring.thymeleaf.cache=false #注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html #设置数据源 #数据库连接用户名 spring.datasource.username=root #数据库连接密码 spring.datasource.password=123456 #驱动 spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver #数据库连接路径 spring.datasource.url=jdbc:mysql://localhost/first?serverTimezone=UTC #连接池类型 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #连接池配置,因为springboot默认是开启了连接池的,它有默认配置,这一段可以忽略 # 初始化大小,最小,最大 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #配置分页插件 #pagehelper分页插件 pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true pagehelper.params=count=countSql #配置mybatis mybatis.type-aliases-package=com.xqt.entity mybatis.mapper-locations=classpath:mapper/*.xml

    三、编写三层代码

    1、entity实体类

    public class Person implements Serializable { private static final long serialVersionUID = 214584259608166847L; private Integer id; private String name; private String sex; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }

    2、Controller控制层

    @Controller public class PersonController { @Autowired private PersonService personService; @GetMapping("/getAllPerson") public String getAllPerson(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){ PageHelper.startPage(pageNum,5); List<Person> list = personService.getAllPerson(); PageInfo<Person> pageInfo = new PageInfo<Person>(list); model.addAttribute("pageInfo",pageInfo); return "list"; } }

    3、service、serviceImpl 业务层

    public interface PersonService { List<Person> getAllPerson(); } @Service("personService") public class PersonServiceImpl implements PersonService { @Resource private PersonDao personDao; @Override public List<Person> getAllPerson() { return this.personDao.getAllPerson(); } }

    4、dao、dao.xm数据访问层

    @Mapper public interface PersonDao { List<Person> getAllPerson(); } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xqt.dao.PersonDao"> <resultMap type="com.xqt.entity.Person" id="PersonMap"> <result property="id" column="id" jdbcType="INTEGER"/> <result property="name" column="name" jdbcType="VARCHAR"/> <result property="sex" column="sex" jdbcType="VARCHAR"/> <result property="age" column="age" jdbcType="INTEGER"/> </resultMap> <!--查询所有数据--> <select id="getAllPerson" resultMap="PersonMap"> select id, name, sex, age from first.person </select> </mapper>

    四、SQL

    /* Navicat Premium Data Transfer Source Server : javaee Source Server Type : MySQL Source Server Version : 50527 Source Host : localhost:3306 Source Schema : first Target Server Type : MySQL Target Server Version : 50527 File Encoding : 65001 Date: 04/10/2020 22:24:19 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for person -- ---------------------------- DROP TABLE IF EXISTS `person`; CREATE TABLE `person` ( `id` int(11) NOT NULL, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Compact; -- ---------------------------- -- Records of person -- ---------------------------- INSERT INTO `person` VALUES (1, '小红', '女', 18); INSERT INTO `person` VALUES (2, '小兰', '女', 20); INSERT INTO `person` VALUES (3, '小绿', '男', 15); INSERT INTO `person` VALUES (4, '小紫', '女', 18); INSERT INTO `person` VALUES (5, '小城', '男', 18); INSERT INTO `person` VALUES (6, 'ii奥里给', '男', 31); INSERT INTO `person` VALUES (7, '热委', '男', 32); SET FOREIGN_KEY_CHECKS = 1;

    五、前端界面

    <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css"> <body> <div align="center"> <table border="1" > <tr> <th>id</th> <th>name</th> <th>sex</th> <th>age</th> </tr> <tr th:each="person:${pageInfo.list}"> <td th:text="${person.id}"></td> <td th:text="${person.name}"></td> <td th:text="${person.sex}"></td> <td th:text="${person.age}"></td> </tr> </table> <p>当前 <span th:text="${pageInfo.pageNum}"></span> 页,总 <span th:text="${pageInfo.pages}"></span> 页,共 <span th:text="${pageInfo.total}"></span> 条记录</p> <div class="ui pagination menu"> <a th:href="@{/getAllPerson}" class="item">首页</a> <a th:href="@{/getAllPerson(pageNum=${pageInfo.hasPreviousPage}?${pageInfo.prePage}:1)}" class="item">上一页</a> <!--循环遍历连续显示的页面,若是当前页就高亮显示,并且没有链接--> <b th:each="nav : ${pageInfo.navigatepageNums}"> <a th:href="'/getAllPerson?pageNum='+${nav}" th:text="${nav}" th:if="${nav != pageInfo.pageNum}" class="item"></a> <span style="font-weight: bold;background: #6faed9;" th:if="${nav == pageInfo.pageNum}" th:text="${nav}" class="item"></span> </b> <a th:href="@{/getAllPerson(pageNum=${pageInfo.hasNextPage}?${pageInfo.nextPage}:${pageInfo.pages})}" class="item">下一页</a> <a th:href="@{/getAllPerson(pageNum=${pageInfo.pages})}" class="item">尾页</a> </div> </div> </body> </html></title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> </body> </html>

    六、运行结果

    Processed: 0.011, SQL: 8