springboot+mybatis实现数据分页(三种方式)
项目准备
1.创建用户表
2.使用spring初始化向导快速创建项目,勾选mybatis,web,jdbc,driver
添加lombok插件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.1</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.hao</groupId><artifactId>spring-boot-crud-end</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-crud-end</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
一、使用原生Java实现分页
1.UserMapper接口
@Mapper
@Repository
public interface UserMapper {int selectCount();List<User> selectUserFindAll();
}
2.整合mybatis(application.yaml)
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/crud?serverTimezone=UTCusername: rootpassword: hao20001010mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.hao.springboot.entity
3.测试dao层(成功)
@SpringBootTest
class SpringBootCrudEndApplicationTests {@AutowiredUserMapper userMapper;@Testvoid contextLoads() {List<User> users = userMapper.selectUserFindAll();for(User user:users){System.out.println(user);}}@Testvoid contextLoads2(){}
}
4.编写service层
public interface UserService {int selectCount();List<User> selectUserByArray(int currentPage,int pageSize);
}
/*** @author:抱着鱼睡觉的喵喵* @date:2020/12/26* @description:*/
@Service
public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic int selectCount() {int count = userMapper.selectCount();return count;}/*** 原始分页逻辑实现* @param currentPage 当前页* @param pageSize 每页的数量* @return*/@Overridepublic List<User> selectUserByArray(int currentPage, int pageSize) {List<User> users = userMapper.selectUserFindAll();int count=selectCount();int startCurrentPage=(currentPage-1)*pageSize; //开启的数据int endCurrentPage=currentPage*pageSize; //结束的数据int totalPage=count/pageSize; //总页数if (currentPage>totalPage || currentPage<=0){return null;}else{return users.subList(startCurrentPage,endCurrentPage);}}
}
5.controller层
@RestController
public class UserController {@AutowiredUserService userService;@GetMapping("/user/{currentPage}/{pageSize}")public List<User> selectFindPart(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserByArray(currentPage, pageSize);if (list==null){throw new UserNotExistException("访问出错!QWQ");}else{return list;}}
}
6.异常处理
public class UserNotExistException extends RuntimeException{private static final long serialVersionUID = 1L;private String msg;public UserNotExistException(String msg) {super("user not exist");this.msg=msg;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}
7.controller异常处理类
/*** @author:抱着鱼睡觉的喵喵* @date:2020/12/26* @description:*/
@ControllerAdvice //处理controller层出现的异常
public class ControllerExceptionHandler {@ExceptionHandler(UserNotExistException.class)@ResponseBody@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) //状态码public Map<String,Object> handlerUserNotExistException(UserNotExistException ex){Map<String,Object> result=new HashMap<>();result.put("msg", ex.getMsg());result.put("message", ex.getMessage());return result;}
}
8.访问http://localhost:8080/user/5/10出现如下
{“msg”:“访问出错!QWQ”,“message”:“user not exist”}
9.访问http://localhost:8080/user/2/3 出现如下
[{“id”:4,“userName”:“sky”,“password”:“789”},{“id”:5,“userName”:“nulls”,“password”:“tom”},{“id”:6,“userName”:“zsh”,“password”:“zsh”}]
总结:
缺点:数据库查询并返回所有的数据,而我们需要的只是极少数符合要求的数据。当数据量少时,还可以接受。当数据库数据量过大时,每次查询对数据库和程序的性能都会产生极大的影响。
二、通过sql语句进行分页操作
1.在UserMapper接口中新增一个方法
@Mapper
@Repository
public interface UserMapper {//原生分页int selectCount();List<User> selectUserFindAll();
//通过sql语句进行分页List<User> selectBySql(Map<String,Object> map);
}
2.UserService接口中新增方法,以及UserServiceImpl类中进行重写
public interface UserService {int selectCount();/*** 原生分页* @param currentPage* @param pageSize* @return*/List<User> selectUserByArray(int currentPage,int pageSize);/*** 通过sql分页* @param currentPage* @param pageSize* @return*/List<User> selectUserBySql(int currentPage,int pageSize);
}
@Service
public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic int selectCount() {int count = userMapper.selectCount();return count;}/*** 原始分页逻辑实现* @param currentPage* @param pageSize* @return*/@Overridepublic List<User> selectUserByArray(int currentPage, int pageSize) {List<User> users = userMapper.selectUserFindAll();int count=selectCount();int startCurrentPage=(currentPage-1)*pageSize; //从第几个数据开始int endCurrentPage=currentPage*pageSize; //结束的数据int totalPage=count/pageSize; //总页数if (currentPage>totalPage || currentPage<=0){return null;}else{return users.subList(startCurrentPage,endCurrentPage);}}
/**
*通过sql语句进行分页
*/@Overridepublic List<User> selectUserBySql(int currentPage, int pageSize) {Map<String,Object> map=new HashMap<>();int startCurrentPage=(currentPage-1)*pageSize; //从第几个数据开始int count=selectCount();int totalPage=count/pageSize; //总页数if (currentPage>totalPage || currentPage<=0){return null;}else{map.put("currentPage",startCurrentPage);map.put("pageSize",pageSize);List<User> list = userMapper.selectBySql(map);return list;}}
}
3.controller层编写
@RestController
public class UserController {@AutowiredUserService userService;
//Java原生实现分页模块@GetMapping("/user/{currentPage}/{pageSize}")public List<User> selectFindByJava(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserByArray(currentPage, pageSize);if (list==null){throw new UserNotExistException("访问出错!QWQ");}else{return list;}}
//sql分页方法模块@GetMapping("/user2/{currentPage}/{pageSize}")public List<User> selectFindBySql(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserBySql(currentPage,pageSize);if (list==null){throw new UserNotExistException("访问出错!QWQ");}else{return list;}}
}
4.UserMapper.xml添加查询条件,使用limit进行分页
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hao.springboot.mapper.UserMapper"><resultMap id="user" type="com.hao.springboot.entity.User"><result column="user_name" property="userName"/><result column="password" property="password"/></resultMap><select id="selectUserFindAll" resultMap="user">select * from user</select><select id="selectCount" resultType="integer">select count(*) from user</select><select id="selectBySql" parameterType="map" resultType="com.hao.springboot.entity.User">select * from user limit #{currentPage} , #{pageSize}</select>
</mapper>
5.启动访问http://localhost:8080/user2/5/10 出现如下
{“msg”:“访问出错!QWQ”,“message”:“user not exist”}
接着正确访问http://localhost:8080/user2/2/2
[{“id”:3,“userName”:“tom”,“password”:“456”},{“id”:4,“userName”:“sky”,“password”:“789”}]
总结:
缺点:虽然这里实现了按需查找,每次检索得到的是指定的数据。但是每次在分页的时候都需要去编写limit语句,很冗余。而且不方便统一管理,维护性较差。所以我们希望能够有一种更方便的分页实现。
三、拦截器实现分页
springboot+mybatis实现数据分页(三种方式)相关推荐
- SpringBoot静态获取 bean的三种方式,你学会了吗?
欢迎关注方志朋的博客,回复"666"获面试宝典 来源:blog.csdn.net/showchi/article/details/97005720 注意:调用者要被spring管理 ...
- discard connection丢失数据_python kafka 生产者发送数据的三种方式
python kafka 生产者发送数据的三种方式 发送方式 同步发送 发送数据耗时最长 有发送数据的状态,不会丢失数据,数据可靠性高 以同步的方式发送消息时,一条一条的发送,对每条消息返回的结果判断 ...
- layui根据条件显示列_templet渲染layui表格数据的三种方式
layui前端框架是我一直在使用,也很好用. 今天记录一下,templet渲染layui表格数据的三种方式. 第一种:直接渲染(对于表格数据样式要求不高) 直接在动态表格字段声明,添加templet属 ...
- ios网络学习------4 UIWebView的加载本地数据的三种方式
ios网络学习------4 UIWebView的加载本地数据的三种方式 分类: IOS2014-06-27 12:56 959人阅读 评论(0) 收藏 举报 UIWebView是IOS内置的浏览器, ...
- python读取图像数据流_浅谈TensorFlow中读取图像数据的三种方式
本文面对三种常常遇到的情况,总结三种读取数据的方式,分别用于处理单张图片.大量图片,和TFRecorder读取方式.并且还补充了功能相近的tf函数. 1.处理单张图片 我们训练完模型之后,常常要用图片 ...
- android sqlite使用之模糊查询数据库数据的三种方式
android sqlite使用之模糊查询数据库数据的三种方式 android应用开发中常常需要记录一下数据,而在查询的时候如何实现模糊查询呢?很少有文章来做这样的介绍,所以这里简单的介绍下三种sql ...
- layui 表格内容写temple函数_templet渲染layui表格数据的三种方式
layui前端框架是我一直在使用,也很好用. 今天记录一下,templet渲染layui表格数据的三种方式. 第一种:直接渲染(对于表格数据样式要求不高) 直接在动态表格字段声明,添加templet属 ...
- mysql数据库删除数据的三种方式:
mysql数据库删除数据的三种方式: delete from table where 直接删除表中的某一行数据,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作.所以delete相 ...
- oracle 批量导入 数据,Oracle批量插入数据的三种方式【推荐】
第一种: begin insert into tableName(column1, column2, column3...) values(value1,value2,value3...); inse ...
最新文章
- input 的read only 和 disable的区别
- 什么?Spring Boot CommandLineRunner 有坑!?
- 机器学习算法基础——线性回归
- Java小结(四)——折半查找、选择排序、冒泡排序
- java控制图片移动_多线程控制图片移动
- Fix an “Unapproved Caller” SecurityAgent Message in Mac OS X
- 关于asp.net利用mono部署到Linux上的一些说明
- Page Object设计模式实践
- 直击标贝科技WAIC2019:深耕语音合成与数据服务 助力语音场景完美落地
- BeanShell用法笔记
- 山景BP1048使用记录
- 编程吸金榜:你排第几?网友神回应了 !
- 使用微搭低代码制作每日菜单小程序
- Englis - 英文字母和音标
- 巴西龟饲养日志----七月底巴西龟状况
- Quartus的SignalTap的使用
- php上传 io err,【Dz上传附件】解决Discuz Server(IO)Error问题
- 剑灵灵动区服务器位置,剑灵灵动内测角色数据如何保存
- 那一阙词,早已波澜-仓央嘉措
- 关于谷歌浏览器页面出现光标闪动,鼠标的焦点没有消失解决
热门文章
- [ASP.NET]EF选一个空表的情况
- Windows 8的无线设置后,竟不能直接更改,目前知道可以通过命令行解决
- SQL中 char、varchar、text 和 nchar、nvarchar、ntext的区别
- 腾讯html5平台,腾讯浏览服务
- python os sys_python os模块sys模块常用方法
- Thumbnailator-图片处理的Google开源Java类库
- 外部中断器1C语言程序,单片机C语言代码:外部中断,按下中断按键LED不亮,LED1正常亮...
- python中paste函数的作用_PIL使用小结(crop和paste函数)
- html中加盒子,在HTML中各类型盒子的基线应如何确定
- c++提供的可有效分配对象空间的运算符是_Python 为什么不支持 i++ 自增语法,不提供 ++ 操作符?