SpringBoot 整合Mybatis + PageHelper 实现分页
前言:
- 现在公司大多数都实现了前后端分离,前端使用Vue、React、AngularJS 等框架,不用完全依赖后端。但是如果对于比较小型的项目,没必要前后端分离,而SpringBoot也基本抛弃了Jsp,使用Thymeleaf模板搭配SpringBoot是个不错的选择。
- 在展示数据时必然需要大量的分页操作,在使用JPA、Mybatis-Plus等持久层框架时,已经自带分页查询操作,无需手动编写,然而在使用Mybatis作为持久层时,需要手动编写分页操作十分麻烦。PageHelper就是用来在Mybatis之上帮助我们实现分页操作。
开发环境:
- IDEA IntelliJ IDEA 2019.3.3 x64
- JDK: 1.8
- SpringBoot: 2.25
- PageHelper: 1.2.13
- Mybatis: 2.1.3 (使用Mybatis作为持久层)
- 数据源:Druid 1.1.23
一、SpringBoot框架搭建
【1】点击:File ---> New ---> Project
【2】这个页面选项是选择SpringBoot需要的启动依赖,在这里可以有很多选项,这里选择 Web 和 SQL中的相应配置,然后点击下一步。(这里的SpringBoot版本有些过高,可以选择使用默认的最新版本)
【3】保存路径,点击FINSH完成。
二、详细配置
1、在pom文件中引入Pagehelper分页插件,Driud数据源(非必需)
<!-- Mybatis 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<!-- Druid 数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
2、创建数据库
数据库名:pagehelperdemo 编码字符集:utf8
CREATE DATABASE `pagehelperdemo`;
USE `pagehelperdemo`;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id主键',
`username` varchar(20) NOT NULL COMMENT '用户名',
`PASSWORD` varchar(20) NOT NULL COMMENT '用户密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
insert into `users`(`id`,`username`,`PASSWORD`) values
(1,'onetest','123'),
(2,'twotest','456'),
(3,'onetest','789'),
(4,'twotest','987'),
(5,'onetest','654'),
(6,'twotest','321'),
(7,'onetest','147'),
(8,'twotest','258'),
(9,'onetest','369'),
(10,'twotest','963');
插入多条数据方便分页查看。
3、配置分页插件
将resource文件夹下的application.properties配置文件改成yml后缀,即application.yml,进行如下配置
server:
port: 8089
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/pagehelperdemo?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
thymeleaf:
encoding: UTF-8
prefix: classpath:/templates/
suffix: .html
cache: false
#mybatis:
# mapper-locations: classpath:/mapper/*.xml #项目中使用注解进行开发
pagehelper:
helper-dialect: mysql # 指定数据库类型
reasonable: true
params: count=countSql
support-methods-arguments: true
三、代码编写
1、创建用户实体类
package com.jia.pojo;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:28
* @QQ: 1498575492
* Description: 用户信息实体类
*/
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2、创建用户持久层接口:UserDaoMapper
package com.jia.mapper;
import com.jia.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:31
* @QQ: 1498575492
* Description: 用户持久层接口
*/
public interface UserDaoMapper {
//查询所有用户
@Select("select id,username,password from users")
List<User> getAllUser();
}
3、创建业务层接口和实现类:UserService、UserServiceImpl
package com.jia.service;
import com.jia.pojo.User;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:35
* @QQ: 1498575492
* Description: 用户业务层接口
*/
public interface UserService {
//查询所有用户
List<User> getAllUser();
}
package com.jia.service.impl;
import com.jia.mapper.UserDaoMapper;
import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:36
* @QQ: 1498575492
* Description: 用户业务层接口实现类
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
UserDaoMapper userDaoMapper;
@Override
public List<User> getAllUser() {
return userDaoMapper.getAllUser();
}
}
4、创建用户控制层:UserController
【1】 编写测试Cntroller,检测是否能查询到数据。
package com.jia.controller;
import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:39
* @QQ: 1498575492
* Description: 用户控制层
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/findAll")
@ResponseBody
public List<User> findUser() {
List<User> userList = userService.getAllUser();
return userList;
}
}
【2】数据查询成功。
【3】修改后的UserController
package com.jia.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: ButterflyStars
* @DateTime: Created in 2020/7/22 1:39
* @QQ: 1498575492
* Description: 用户控制层
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* @param model
* @param pageNum 当前页数
* @return
*/
@GetMapping("/findAll")
public String findUser(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
PageHelper.startPage(pageNum,5); // 默认从第一页开始,每页展示五条数据
List<User> userList = userService.getAllUser();
PageInfo<User> pageInfo = new PageInfo<>(userList);
model.addAttribute("pageInfo",pageInfo);
return "index";
}
}
5、添加 MapperScan 注解
修改 启动文件,在类前添加 MapperScan 注解,修改后如下:
package com.jia;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.jia.mapper")
public class PagehelperDemoApplication {
public static void main(String[] args) {
SpringApplication.run(PagehelperDemoApplication.class, args);
}
}
6、创建index.html页面,引入Thymeleaf依赖
注意:对user进行取值时,属性会有红色波浪线提示,并不影响运行。
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>分页测试</title>
</head>
<body>
<h3>查询所有用户</h3>
<table border="1">
<tr>
<th>id</th>
<th>name</th>
<th>password</th>
</tr>
<tr th:each="user:${pageInfo.list}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
<p>当前 <span th:text="${pageInfo.pageNum}"></span> 页,总 <span th:text="${pageInfo.pages}"></span> 页,共 <span th:text="${pageInfo.total}"></span> 条记录</p>
<a th:href="@{/user/findAll}">首页</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.hasPreviousPage}?${pageInfo.prePage}:1)}">上一页</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.hasNextPage}?${pageInfo.nextPage}:${pageInfo.pages})}">下一页</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.pages})}">尾页</a>
</body>
</html>
四、运行测试
启动 SpringBoot 工程,在浏览器输入:http://localhost:8089/user/findAll,可以看到网页显示用户信息表格,点击上一页、下一页可以进行页面切换显示数据。
SpringBoot 整合Mybatis + PageHelper 实现分页的更多相关文章
- springboot整合mybatis+pageHelper
springboot整合mybatis+pageHelper 〇.搭建sporingboot环境,已经整合mybatis环境,本篇主要是添加pageHelper工具 一.添加依赖 <!-- 分页 ...
- SpringBoot整合mybatis使用pageHelper插件进行分页操作
SpringBoot整合mybatis分页操作 SpringBoot整合Mybatis进行分页操作,这里需要使用Mybatis的分页插件:pageHelper, 关于pageHelper的介绍,请查看 ...
- SpringBoot整合系列-PageHelper分页插件
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9971043.html SpringBoot整合MyBatis分页插件PageHelper ...
- SpringBoot整合Mybatis关于分页查询的方法
最近公司在用到SpringBoot整合Mybatis时当web端页面数据增多时需要使用分页查询以方便来展示数据.本人对分页查询进行了一些步骤的总结,希望能够帮助到有需要的博友.如有更好的方式,也希望评 ...
- SpringBoot+Mybatis+PageHelper实现分页
SpringBoot+Mybatis+PageHelper实现分页 mybatis自己没有分页功能,我们可以通过PageHelper工具来实现分页,非常简单方便 第一步:添加依赖 <depend ...
- SpringBoot集成Mybatis并具有分页功能PageHelper
SpringBoot集成Mybatis并具有分页功能PageHelper 环境:IDEA编译工具 第一步:生成测试的数据库表和数据 SET FOREIGN_KEY_CHECKS=0; ...
- SpringBoot整合Mybatis之项目结构、数据源
已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...
- springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)
这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...
- SpringBoot整合Mybatis之进门篇
已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...
随机推荐
- 黎活明8天快速掌握android视频教程--25_网络通信之资讯客户端
1 该项目的主要功能是:后台通过xml或者json格式返回后台的视频资讯,然后Android客户端界面显示出来 首先后台新建立一个java web后台 采用mvc的框架 所以的servlet都放在se ...
- Struts2 执行流程 以及 Action与Servlet比较 (个人理解)
上图提供了struts2的执行流程.如下: 1:从客户端发出请求(HTTPServletRequest). 2:请求经过各种过滤器(filter),注:一般情况下,如SiteMesh等其他过滤器要放在 ...
- leetcode 6 z字型变换
执行用时 :64 ms, 在所有 Python3 提交中击败了99.74%的用户由题目可知 我们的最终字符串会被摆成 numRows 行,那我们理解为 最终结果是numRows个字符串相加 先建立等于 ...
- Apache Dubbo Provider默认反序列漏洞复现(CVE-2020-1948)
Apache Dubbo Provider默认反序列漏洞(CVE-2020-1948) 0x01 搭建漏洞环境 漏洞介绍 2020年06月23日, 360CERT监测发现Apache Dubbo 官方 ...
- pandas | 使用pandas进行数据处理——Series篇
本文始发于个人公众号:TechFlow,原创不易,求个关注 上周我们关于Python中科学计算库Numpy的介绍就结束了,今天我们开始介绍一个新的常用的计算工具库,它就是大名鼎鼎的Pandas. Pa ...
- 03-springboot整合elasticsearch-源码初识
前面两个小节已经知道了spring boot怎么整合es,以及es的简单使用,但是springboot中是怎么和es服务器交互的.我们可以简单了解一下.要看一下源码 在看源码的同时,先要对sp ...
- OAuth 2.0 授权方式讲解,规范实践和应用
基于实践说规范 网上看了一些OAuth 2.0的授权方法,尽管讲解的没有什么逻辑性错误,但是存在一个问题,那就是单纯的讲解协议规范却脱离了实际的应用,缺少干货,所以才有了这篇文章,内容基于实际业务进行 ...
- chrome本地调试跨域问题
1.关闭chrome浏览器(全部) 我们可以通过使用chrome命令行启动参数来改变chrome浏览器的设置,具体的启动参数说明参考这篇介绍.https://code.google.com/p/xia ...
- 14.刚体组件Rigidbody
刚体组件是物理类组件,添加有刚体组件的物体,会像现实生活中的物体一样有重力.会下落.能碰撞. 给物体添加刚体: 选中游戏物体->菜单Component->Physics->Rigid ...
- BUUCTF-Misc-No.1
# BUUCTF-Misc # 签到 flag{buu_ctf} 金三胖 说实话直接看出来flag{he11ohongke} 二维码 直接binwalk扫一下,-e分离就出来一个带锁的zip爆破一下就 ...