项目准备

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.Driver
url: jdbc:mysql://localhost:3306/crud?serverTimezone=UTC
username: root
password: hao20001010 mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.hao.springboot.entity

3.测试dao层(成功

@SpringBootTest
class SpringBootCrudEndApplicationTests { @Autowired
UserMapper userMapper; @Test
void contextLoads() {
List<User> users = userMapper.selectUserFindAll();
for(User user:users){
System.out.println(user);
}
} @Test
void 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 { @Autowired
UserMapper userMapper; @Override
public int selectCount() {
int count = userMapper.selectCount();
return count;
} /**
* 原始分页逻辑实现
* @param currentPage 当前页
* @param pageSize 每页的数量
* @return
*/
@Override
public 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 { @Autowired
UserService 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 { @Autowired
UserMapper userMapper; @Override
public int selectCount() {
int count = userMapper.selectCount();
return count;
} /**
* 原始分页逻辑实现
* @param currentPage
* @param pageSize
* @return
*/
@Override
public 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语句进行分页
*/
@Override
public 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 { @Autowired
UserService 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 mapper
PUBLIC "-//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实现数据分页(三种方式)的更多相关文章

  1. Linux就这个范儿 第15章 七种武器 linux 同步IO: sync、fsync与fdatasync Linux中的内存大页面huge page/large page David Cutler Linux读写内存数据的三种方式

    Linux就这个范儿 第15章 七种武器  linux 同步IO: sync.fsync与fdatasync   Linux中的内存大页面huge page/large page  David Cut ...

  2. ios网络学习------4 UIWebView的加载本地数据的三种方式

    ios网络学习------4 UIWebView的加载本地数据的三种方式 分类: IOS2014-06-27 12:56 959人阅读 评论(0) 收藏 举报 UIWebView是IOS内置的浏览器, ...

  3. Linux就这个范儿 第18章 这里也是鼓乐笙箫 Linux读写内存数据的三种方式

    Linux就这个范儿 第18章  这里也是鼓乐笙箫  Linux读写内存数据的三种方式 P703 Linux读写内存数据的三种方式 1.read  ,write方式会在用户空间和内核空间不断拷贝数据, ...

  4. MATLAB 显示输出数据的三种方式

    MATLAB 显示输出数据的三种方式 ,转载 https://blog.csdn.net/qq_35318838/article/details/78780412 1.改变数据格式 当数据重复再命令行 ...

  5. ajax数据提交数据的三种方式和jquery的事件委托

    ajax数据提交数据的三种方式 1.只是字符串或数字 $.ajax({ url: 'http//www.baidu.com', type: 'GET/POST', data: {'k1':'v1'}, ...

  6. Struts2(四.注册时检查用户名是否存在及Action获取数据的三种方式)

    一.功能 1.用户注册页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  7. iOS --- UIWebView的加载本地数据的三种方式

    UIWebView是IOS内置的浏览器,可以浏览网页,打开文档  html/htm  pdf   docx  txt等格式的文件.  safari浏览器就是通过UIWebView做的. 服务器将MIM ...

  8. android sqlite使用之模糊查询数据库数据的三种方式

    android应用开发中常常需要记录一下数据,而在查询的时候如何实现模糊查询呢?很少有文章来做这样的介绍,所以这里简单的介绍下三种sqlite的模糊查询方式,直接上代码把: package com.e ...

  9. jQuery中通过JSONP来跨域获取数据的三种方式

    第一种方法是在ajax函数中设置dataType为'jsonp' $.ajax({ dataType: 'jsonp', url: 'http://www.a.com/user?id=123', su ...

随机推荐

  1. Android 12(S) 图形显示系统 - 初识ANativeWindow/Surface/SurfaceControl(七)

    题外话 "行百里者半九十",是说步行一百里路,走过九十里,只能算是走了一半.因为步行越接近目的地,走起来越困难.借指凡事到了接近成功,往往是最吃力.最艰难的时段.劝人做事贵在坚持, ...

  2. 笔记软件-Obsidian(相关资料分享)

    Obsidian(黑曜石) 是一个功能强大的知识管理软件,是一款功能强大的带有关系图谱功能的双向链笔记,它可基于纯文本Markdown文件的本地文件夹上运行 Obsidian是一个支持markdown ...

  3. mysql or in union all 使用方法

    or的用法 select * from bt where bt.ID =98 or bt.ID = 1222 or bt.ID = 8903; in 的用法 select * from bt wher ...

  4. Docker-compose 搭建 Harbor私有仓库

    一. 安装docker-compose 1. 下载docker-compose的最新版本 curl -L "https://github.com/docker/compose/release ...

  5. Floyd算法 解决多元汇最短路问题

    接下来是图论问题求解最短路问题的最后一个,求解多元汇最短路问题 我们之前一般都是问1-n的最短路径,这里我们要能随便去问i到j的最短路径: 这里介绍一下Floyd算法:我们只有一个d[maxn][ma ...

  6. [SHA2017](web) writeup

    [SHA2017](web) writeup Bon Appétit (100) 打开页面查看源代码,发现如下 自然而然想到php伪协议,有个坑,看不了index.php,只能看 .htaccess ...

  7. 【网鼎杯】jocker--部分代码加壳逆向处理

    Main函数,用户输入flag,长度为24位 Wrong函数进行了简单的异或操作 Omg函数进行异或操作,根据提示来看应该是假check Encrypt无法生成伪代码 发现有加壳以及自修改,下断点动调 ...

  8. Jquery是什么?有什么作用?

    Jquery是继prototype之后又一个优秀的Javascrīpt框架.它是轻量级的js库(压缩后只有21k) ,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safar ...

  9. 什么是 Hystrix 断路器?我们需要它吗?

    由于某些原因,employee-consumer 公开服务会引发异常.在这种情况下使用Hystrix 我们定义了一个回退方法.如果在公开服务中发生异常,则回退方法返回一些默认值. 如果 firstPag ...

  10. Redis 回收进程如何工作的?

    一个客户端运行了新的命令,添加了新的数据.Redi 检查内存使用情况,如 果大于 maxmemory 的限制, 则根据设定好的策略进行回收.一个新的命令被执 行,等等.所以我们不断地穿越内存限制的边界 ...