PageHelper在SpringBoot+Mybatis下的使用

Spring Boot 同时被 2 个专栏收录
31 篇文章 0 订阅
6 篇文章 0 订阅

说明

MyBatis 分页插件 PageHelper,如果你也在用 MyBatis,建议尝试该分页插件,这一定是最方便使用的分页插件。分页插件支持任何复杂的单表、多表分页。

官网戳-->https://pagehelper.github.io/

官方文档戳--> 文档

Github项目戳-->pagehelper-spring-boot

快速开始

首先给出项目结构图:

1 初始化和配置

首先更新pom.xml文件:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.yunlingfly</groupId>
    <artifactId>pagehelperdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>pagehelperdemo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.10</version>
        </dependency>
        <!-- 配置阿里druid连接池,通过改变spring.datasource.type设置数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

然后更新application.yml:

server:
  port: 8081
spring:
  application:
    name: springboot-mybatis-pagehelper
  datasource:
    # 使用阿里的Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    # 填写你数据库的url、登录名、密码和数据库名,IP地址如果使用docker-mysql则是192.168.99.100
    url: jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8
    username: root
    password: root
    # 连接池的配置信息
    # 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
info:
  version: 0.1
pagehelper:
  # 数据库方言
  helper-dialect: mysql
  # 判断合理性比如负数和超过最大总数
  reasonable: true
  # 支持方法参数
  support-methods-arguments: true

给出初始化数据库脚本test.sql,这个SQL来自于PageHelper官方给的SQL例子:

CREATE DATABASE `test` CHARACTER SET 'utf8';

USE `test`;

DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `countryname` varchar(255) DEFAULT NULL COMMENT '名称',
  `countrycode` varchar(255) DEFAULT NULL COMMENT '代码',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='国家信息';

DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `state` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='市级信息';

CREATE TABLE `user_info` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL DEFAULT '' COMMENT '用户名',
  `password` varchar(32) DEFAULT NULL COMMENT '密码',
  `usertype` varchar(2) DEFAULT NULL COMMENT '用户类型',
  `enabled` int(2) DEFAULT NULL COMMENT '是否可用',
  `realname` varchar(32) DEFAULT NULL COMMENT '真实姓名',
  `qq` varchar(14) DEFAULT NULL COMMENT 'QQ',
  `email` varchar(100) DEFAULT NULL,
  `tel` varchar(255) DEFAULT NULL COMMENT '联系电话',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='用户信息表';

-- 用户信息
INSERT INTO `user_info` VALUES ('1', 'test1', '12345678', '1', null, null, null, null, null);
INSERT INTO `user_info` VALUES ('2', 'test2', 'aaaa', '2', null, null, null, null, null);
INSERT INTO `user_info` VALUES ('3', 'test3', 'bbbb', '1', null, null, null, null, null);
INSERT INTO `user_info` VALUES ('4', 'test4', 'cccc', '2', null, null, null, null, null);
INSERT INTO `user_info` VALUES ('5', 'test5', 'dddd', '1', null, null, null, null, null);

-- 国家信息
INSERT INTO `country` VALUES (1,'Angola','AO');
INSERT INTO `country` VALUES (2,'Afghanistan','AF');
INSERT INTO `country` VALUES (3,'Albania','AL');
INSERT INTO `country` VALUES (4,'Algeria','DZ');
INSERT INTO `country` VALUES (5,'Andorra','AD');
INSERT INTO `country` VALUES (6,'Anguilla','AI');
INSERT INTO `country` VALUES (7,'Antigua and Barbuda','AG');
INSERT INTO `country` VALUES (8,'Argentina','AR');
INSERT INTO `country` VALUES (9,'Armenia','AM');
INSERT INTO `country` VALUES (10,'Australia','AU');
INSERT INTO `country` VALUES (11,'Austria','AT');
INSERT INTO `country` VALUES (12,'Azerbaijan','AZ');
INSERT INTO `country` VALUES (13,'Bahamas','BS');
INSERT INTO `country` VALUES (14,'Bahrain','BH');
INSERT INTO `country` VALUES (15,'Bangladesh','BD');
INSERT INTO `country` VALUES (16,'Barbados','BB');
INSERT INTO `country` VALUES (17,'Belarus','BY');
INSERT INTO `country` VALUES (18,'Belgium','BE');
INSERT INTO `country` VALUES (19,'Belize','BZ');
INSERT INTO `country` VALUES (20,'Benin','BJ');
INSERT INTO `country` VALUES (21,'Bermuda Is.','BM');
INSERT INTO `country` VALUES (22,'Bolivia','BO');
INSERT INTO `country` VALUES (23,'Botswana','BW');
INSERT INTO `country` VALUES (24,'Brazil','BR');
INSERT INTO `country` VALUES (25,'Brunei','BN');
INSERT INTO `country` VALUES (26,'Bulgaria','BG');
INSERT INTO `country` VALUES (27,'Burkina-faso','BF');
INSERT INTO `country` VALUES (28,'Burma','MM');
INSERT INTO `country` VALUES (29,'Burundi','BI');
INSERT INTO `country` VALUES (30,'Cameroon','CM');
INSERT INTO `country` VALUES (31,'Canada','CA');
INSERT INTO `country` VALUES (32,'Central African Republic','CF');
INSERT INTO `country` VALUES (33,'Chad','TD');
INSERT INTO `country` VALUES (34,'Chile','CL');
INSERT INTO `country` VALUES (35,'China','CN');
INSERT INTO `country` VALUES (36,'Colombia','CO');
INSERT INTO `country` VALUES (37,'Congo','CG');
INSERT INTO `country` VALUES (38,'Cook Is.','CK');
INSERT INTO `country` VALUES (39,'Costa Rica','CR');
INSERT INTO `country` VALUES (40,'Cuba','CU');
INSERT INTO `country` VALUES (41,'Cyprus','CY');
INSERT INTO `country` VALUES (42,'Czech Republic','CZ');
INSERT INTO `country` VALUES (43,'Denmark','DK');
INSERT INTO `country` VALUES (44,'Djibouti','DJ');
INSERT INTO `country` VALUES (45,'Dominica Rep.','DO');
INSERT INTO `country` VALUES (46,'Ecuador','EC');
INSERT INTO `country` VALUES (47,'Egypt','EG');
INSERT INTO `country` VALUES (48,'EI Salvador','SV');
INSERT INTO `country` VALUES (49,'Estonia','EE');
INSERT INTO `country` VALUES (50,'Ethiopia','ET');
INSERT INTO `country` VALUES (51,'Fiji','FJ');
INSERT INTO `country` VALUES (52,'Finland','FI');
INSERT INTO `country` VALUES (53,'France','FR');
INSERT INTO `country` VALUES (54,'French Guiana','GF');
INSERT INTO `country` VALUES (55,'Gabon','GA');
INSERT INTO `country` VALUES (56,'Gambia','GM');
INSERT INTO `country` VALUES (57,'Georgia','GE');
INSERT INTO `country` VALUES (58,'Germany','DE');
INSERT INTO `country` VALUES (59,'Ghana','GH');
INSERT INTO `country` VALUES (60,'Gibraltar','GI');
INSERT INTO `country` VALUES (61,'Greece','GR');
INSERT INTO `country` VALUES (62,'Grenada','GD');
INSERT INTO `country` VALUES (63,'Guam','GU');
INSERT INTO `country` VALUES (64,'Guatemala','GT');
INSERT INTO `country` VALUES (65,'Guinea','GN');
INSERT INTO `country` VALUES (66,'Guyana','GY');
INSERT INTO `country` VALUES (67,'Haiti','HT');
INSERT INTO `country` VALUES (68,'Honduras','HN');
INSERT INTO `country` VALUES (69,'Hongkong','HK');
INSERT INTO `country` VALUES (70,'Hungary','HU');
INSERT INTO `country` VALUES (71,'Iceland','IS');
INSERT INTO `country` VALUES (72,'India','IN');
INSERT INTO `country` VALUES (73,'Indonesia','ID');
INSERT INTO `country` VALUES (74,'Iran','IR');
INSERT INTO `country` VALUES (75,'Iraq','IQ');
INSERT INTO `country` VALUES (76,'Ireland','IE');
INSERT INTO `country` VALUES (77,'Israel','IL');
INSERT INTO `country` VALUES (78,'Italy','IT');
INSERT INTO `country` VALUES (79,'Jamaica','JM');
INSERT INTO `country` VALUES (80,'Japan','JP');
INSERT INTO `country` VALUES (81,'Jordan','JO');
INSERT INTO `country` VALUES (82,'Kampuchea (Cambodia )','KH');
INSERT INTO `country` VALUES (83,'Kazakstan','KZ');
INSERT INTO `country` VALUES (84,'Kenya','KE');
INSERT INTO `country` VALUES (85,'Korea','KR');
INSERT INTO `country` VALUES (86,'Kuwait','KW');
INSERT INTO `country` VALUES (87,'Kyrgyzstan','KG');
INSERT INTO `country` VALUES (88,'Laos','LA');
INSERT INTO `country` VALUES (89,'Latvia','LV');
INSERT INTO `country` VALUES (90,'Lebanon','LB');
INSERT INTO `country` VALUES (91,'Lesotho','LS');
INSERT INTO `country` VALUES (92,'Liberia','LR');
INSERT INTO `country` VALUES (93,'Libya','LY');
INSERT INTO `country` VALUES (94,'Liechtenstein','LI');
INSERT INTO `country` VALUES (95,'Lithuania','LT');
INSERT INTO `country` VALUES (96,'Luxembourg','LU');
INSERT INTO `country` VALUES (97,'Macao','MO');
INSERT INTO `country` VALUES (98,'Madagascar','MG');
INSERT INTO `country` VALUES (99,'Malawi','MW');
INSERT INTO `country` VALUES (100,'Malaysia','MY');
INSERT INTO `country` VALUES (101,'Maldives','MV');
INSERT INTO `country` VALUES (102,'Mali','ML');
INSERT INTO `country` VALUES (103,'Malta','MT');
INSERT INTO `country` VALUES (104,'Mauritius','MU');
INSERT INTO `country` VALUES (105,'Mexico','MX');
INSERT INTO `country` VALUES (106,'Moldova, Republic of','MD');
INSERT INTO `country` VALUES (107,'Monaco','MC');
INSERT INTO `country` VALUES (108,'Mongolia','MN');
INSERT INTO `country` VALUES (109,'Montserrat Is','MS');
INSERT INTO `country` VALUES (110,'Morocco','MA');
INSERT INTO `country` VALUES (111,'Mozambique','MZ');
INSERT INTO `country` VALUES (112,'Namibia','NA');
INSERT INTO `country` VALUES (113,'Nauru','NR');
INSERT INTO `country` VALUES (114,'Nepal','NP');
INSERT INTO `country` VALUES (115,'Netherlands','NL');
INSERT INTO `country` VALUES (116,'New Zealand','NZ');
INSERT INTO `country` VALUES (117,'Nicaragua','NI');
INSERT INTO `country` VALUES (118,'Niger','NE');
INSERT INTO `country` VALUES (119,'Nigeria','NG');
INSERT INTO `country` VALUES (120,'North Korea','KP');
INSERT INTO `country` VALUES (121,'Norway','NO');
INSERT INTO `country` VALUES (122,'Oman','OM');
INSERT INTO `country` VALUES (123,'Pakistan','PK');
INSERT INTO `country` VALUES (124,'Panama','PA');
INSERT INTO `country` VALUES (125,'Papua New Cuinea','PG');
INSERT INTO `country` VALUES (126,'Paraguay','PY');
INSERT INTO `country` VALUES (127,'Peru','PE');
INSERT INTO `country` VALUES (128,'Philippines','PH');
INSERT INTO `country` VALUES (129,'Poland','PL');
INSERT INTO `country` VALUES (130,'French Polynesia','PF');
INSERT INTO `country` VALUES (131,'Portugal','PT');
INSERT INTO `country` VALUES (132,'Puerto Rico','PR');
INSERT INTO `country` VALUES (133,'Qatar','QA');
INSERT INTO `country` VALUES (134,'Romania','RO');
INSERT INTO `country` VALUES (135,'Russia','RU');
INSERT INTO `country` VALUES (136,'Saint Lueia','LC');
INSERT INTO `country` VALUES (137,'Saint Vincent','VC');
INSERT INTO `country` VALUES (138,'San Marino','SM');
INSERT INTO `country` VALUES (139,'Sao Tome and Principe','ST');
INSERT INTO `country` VALUES (140,'Saudi Arabia','SA');
INSERT INTO `country` VALUES (141,'Senegal','SN');
INSERT INTO `country` VALUES (142,'Seychelles','SC');
INSERT INTO `country` VALUES (143,'Sierra Leone','SL');
INSERT INTO `country` VALUES (144,'Singapore','SG');
INSERT INTO `country` VALUES (145,'Slovakia','SK');
INSERT INTO `country` VALUES (146,'Slovenia','SI');
INSERT INTO `country` VALUES (147,'Solomon Is','SB');
INSERT INTO `country` VALUES (148,'Somali','SO');
INSERT INTO `country` VALUES (149,'South Africa','ZA');
INSERT INTO `country` VALUES (150,'Spain','ES');
INSERT INTO `country` VALUES (151,'Sri Lanka','LK');
INSERT INTO `country` VALUES (152,'St.Lucia','LC');
INSERT INTO `country` VALUES (153,'St.Vincent','VC');
INSERT INTO `country` VALUES (154,'Sudan','SD');
INSERT INTO `country` VALUES (155,'Suriname','SR');
INSERT INTO `country` VALUES (156,'Swaziland','SZ');
INSERT INTO `country` VALUES (157,'Sweden','SE');
INSERT INTO `country` VALUES (158,'Switzerland','CH');
INSERT INTO `country` VALUES (159,'Syria','SY');
INSERT INTO `country` VALUES (160,'Taiwan','TW');
INSERT INTO `country` VALUES (161,'Tajikstan','TJ');
INSERT INTO `country` VALUES (162,'Tanzania','TZ');
INSERT INTO `country` VALUES (163,'Thailand','TH');
INSERT INTO `country` VALUES (164,'Togo','TG');
INSERT INTO `country` VALUES (165,'Tonga','TO');
INSERT INTO `country` VALUES (166,'Trinidad and Tobago','TT');
INSERT INTO `country` VALUES (167,'Tunisia','TN');
INSERT INTO `country` VALUES (168,'Turkey','TR');
INSERT INTO `country` VALUES (169,'Turkmenistan','TM');
INSERT INTO `country` VALUES (170,'Uganda','UG');
INSERT INTO `country` VALUES (171,'Ukraine','UA');
INSERT INTO `country` VALUES (172,'United Arab Emirates','AE');
INSERT INTO `country` VALUES (173,'United Kiongdom','GB');
INSERT INTO `country` VALUES (174,'United States of America','US');
INSERT INTO `country` VALUES (175,'Uruguay','UY');
INSERT INTO `country` VALUES (176,'Uzbekistan','UZ');
INSERT INTO `country` VALUES (177,'Venezuela','VE');
INSERT INTO `country` VALUES (178,'Vietnam','VN');
INSERT INTO `country` VALUES (179,'Yemen','YE');
INSERT INTO `country` VALUES (180,'Yugoslavia','YU');
INSERT INTO `country` VALUES (181,'Zimbabwe','ZW');
INSERT INTO `country` VALUES (182,'Zaire','ZR');
INSERT INTO `country` VALUES (183,'Zambia','ZM');

-- 城市信息
INSERT INTO `city` VALUES ('1', '石家庄', '河北');
INSERT INTO `city` VALUES ('2', '邯郸', '河北');

2 开始写代码~

先写个启动类PagehelperdemoApplication.java

package cn.yunlingfly.pagehelperdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@MapperScan("cn.yunlingfly.pagehelperdemo.mapper")
@ServletComponentScan
public class PagehelperdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(PagehelperdemoApplication.class, args);
    }
}

编写实体类BaseEntity.java与Country.java:

package cn.yunlingfly.pagehelperdemo.entity;

public class BaseEntity {

    private Integer id;

    private Integer page = 1;

    private Integer rows = 10;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}
package cn.yunlingfly.pagehelperdemo.entity;

public class Country extends BaseEntity {
    /**
     * 名称
     */
    private String countryname;

    /**
     * 代码
     */
    private String countrycode;

    /**
     * 获取名称
     *
     * @return countryname - 名称
     */
    public String getCountryname() {
        return countryname;
    }

    /**
     * 设置名称
     *
     * @param countryname 名称
     */
    public void setCountryname(String countryname) {
        this.countryname = countryname;
    }

    /**
     * 获取代码
     *
     * @return countrycode - 代码
     */
    public String getCountrycode() {
        return countrycode;
    }

    /**
     * 设置代码
     *
     * @param countrycode 代码
     */
    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }

}

编写阿里的Druid连接池配置DruidStatViewServlet.java和DruidStatFilter.java:

package cn.yunlingfly.pagehelperdemo.servlet;

import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns = "/druid/*",
        initParams = {
                @WebInitParam(name = "allow", value = "127.0.0.1,192.168.163.1"),// IP白名单(没有配置或者为空,则允许所有访问)
                @WebInitParam(name = "deny", value = "192.168.1.73"),// IP黑名单 (存在共同时,deny优先于allow)
                @WebInitParam(name = "loginUsername", value = "admin"),// 用户名
                @WebInitParam(name = "loginPassword", value = "123456"),// 密码
                @WebInitParam(name = "resetEnable", value = "false")// 禁用HTML页面上的“Reset All”功能
        })
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = -2688872071445249539L;

}
package cn.yunlingfly.pagehelperdemo.filter;

import com.alibaba.druid.support.http.WebStatFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
        }
)
public class DruidStatFilter extends WebStatFilter {
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("No.3 Druid filter initialized successfully");
        super.init(config);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        System.out.println("No.3 Druid filter");
        super.doFilter(request, response, chain);
    }
}

编写一个Mybatis的Mapper接口IPageHelperMapper.java:

package cn.yunlingfly.pagehelperdemo.mapper;

import cn.yunlingfly.pagehelperdemo.entity.Country;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface IPageHelperMapper {
    @Select("SELECT * FROM country")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "countryname", column = "countryname"),
            @Result(property = "countrycode", column = "countrycode")
    })
    List<Country> getAll();

    @Select("SELECT count(*) from country")
    Integer selectCount();
}

编写一个Service接口IPageHelperService.java:

package cn.yunlingfly.pagehelperdemo.service;

import cn.yunlingfly.pagehelperdemo.entity.Country;

import java.util.List;

public interface IPageHelperService {
    // 列出所有城市
    List<Country> listAll(int pageNum, int pageSize);

    // 判断最大值
    Boolean greaterThanNums(int pageNum, int pageSize);
}

接口实现类PageHelperServiceImpl.java:

package cn.yunlingfly.pagehelperdemo.service.impl;

import cn.yunlingfly.pagehelperdemo.entity.Country;
import cn.yunlingfly.pagehelperdemo.mapper.IPageHelperMapper;
import cn.yunlingfly.pagehelperdemo.service.IPageHelperService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PageHelperServiceImpl implements IPageHelperService {
    @Autowired
    IPageHelperMapper iPageHelperMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public List<Country> listAll(int pageNum, int pageSize) {
        // 这是最重要的一步,开启分页
        PageHelper.startPage(pageNum, pageSize);

        return iPageHelperMapper.getAll();
    }

    @Override
    public Boolean greaterThanNums(int pageNum, int pageSize) {
        // 算法:除第一页以外(第一页就算不足也要全部展示出来),如果上一页就已经到达最大总数,则后面几页都不该存在。其他负数的情况PageHelper已经帮你处理了,有需要也可以自己在这编写算法
        if (pageNum > 1 && (pageNum - 1) * pageSize > iPageHelperMapper.selectCount()) return true;
        else return false;
    }
}

编写一个Controller层PageHelperController.java:

package cn.yunlingfly.pagehelperdemo.controller;

import cn.yunlingfly.pagehelperdemo.entity.Country;
import cn.yunlingfly.pagehelperdemo.service.IPageHelperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class PageHelperController {
    @Autowired
    IPageHelperService pageHelperService;

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public List<Country> getAllCount(int pageNum, int pageSize) {
        // 如果超过最大总数则直接返回null
        if (pageHelperService.greaterThanNums(pageNum, pageSize)) return null;

        return pageHelperService.listAll(pageNum, pageSize);
    }
}

--------------------------------------------------代码结束---------------------------------------

运行结果

因为是GET请求直接打开浏览器输入http://localhost:8081/getAll?pageNum=1&pageSize=10即可看到结果,我加了一点小优化,如果下一页不存在的话直接返回null(请求总行数>数据库总行数)有需要的话可以更改PageHelperServiceImpl类定制自己的需求

返回null的:

最后放上笔者该项目的github地址(IDEA写的,直接用IDEA->open等maven跑完即可)戳-->https://github.com/Yunlingfly/pagehelper-springboot

  • 0
    点赞
  • 1
    评论
  • 2
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页

打赏作者

芸灵fly

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值