SpringBoot整合MyBatisPlus的PageHelper插件实现分页

SpringBoot整合MyBatisPlus的PageHelper插件

在SpringBoot项目中我们经常需要对查询的数据进行分页,其实我们可以复用查询所有数据的数据层接口,然后借助PageHelper插件对查询的数据进行分页,然后返回给前端

配置

添加POM依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         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.5.1</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mongo-admin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>mongo-core</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

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

        <!--mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <!--代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--velocity模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

        <!--swagger3-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <!-- 此配置不可缺,否则mybatis的Mapper.xml将会丢失 -->
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--指定资源的位置-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>


</project>

添加YML配置

#默认datasource配置
#spring:
#  datasource:
#    type: com.alibaba.druid.pool.DruidDataSource
#    driver-class-name: com.mysql.cj.jdbc.Driver
#    url: jdbc:mysql://localhost:3306/mongo?serverTimezone=UTC
#    username: root
#    password: root


#整合Druid连接池的datasource配置
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mongo?characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initial-size: 5
    min-idle: 5
    max-active: 20
    max-wait: 60000
    test-while-idle: true
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 30000
    validation-query: select 'x'
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true
    filters: stat,wall,slf4j
    max-pool-prepared-statement-per-connection-size: 20
    use-global-data-source-stat: true
    connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000


#服务端口
server:
  port: 80


#PageHelper配置
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true


#Spring整合MP
mybatis-plus:
  #定义别名包
  type-aliases-package: com.example.mongoadmin.entity
  #导入映射文件
  mapper-locations: classpath:/mapper/*.xml
  #开启驼峰映射
  configuration:
    map-underscore-to-camel-case: true


#为com.example.mongoadmin.mapper包下的SQL执行打印日志
logging:
  level:
    com.example.mongoadmin.mapper: info

编写代码

因为我们可以复用查询全部的数据层代码,即Mapper代码,然后使用PageHelper去做分页,所以我们只需要在Service层实现一个分页查询的服务即可

image-20230624212632716

Service

接口

package com.example.mongoadmin.service;

import com.example.mongoadmin.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * <p>
 * 用户管理 服务类
 * </p>
 *
 * @author ZJ
 * @since 2023-06-24
 */
public interface IUserService extends IService<User> {
    
    

    List<User> findAll();

    PageInfo findByPage(int pageNum, int pageSize);

}


具体实现

package com.example.mongoadmin.service.impl;

import com.example.mongoadmin.entity.User;
import com.example.mongoadmin.mapper.UserMapper;
import com.example.mongoadmin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户管理 服务实现类
 * </p>
 *
 * @author ZJ
 * @since 2023-06-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
    
    
        return userMapper.findAll();
    }

    @Override
    public PageInfo findByPage(int pageNum, int pageSize) {
    
    
        PageHelper.startPage(pageNum, pageSize);
        List<User> all = userMapper.findAll();
        PageInfo<User> pageInfo = new PageInfo<User>(all);
        return pageInfo;
    }

}

说明:我们使用PageHelper.startPage进行分页,然后调用userMapper.findAll()查询分页数据,最后使用PageInfo封装数据返回

Controller

前端通过访问/user/findByPage接口并传递分页参数访问服务

package com.example.mongoadmin.controller;

import com.example.mongoadmin.entity.User;
import com.example.mongoadmin.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户管理 前端控制器
 * </p>
 *
 * @author ZJ
 * @since 2023-06-24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @Resource
    private IUserService userService;

    @GetMapping("/findAll")
    public List<User> findAll() {
    
    
        return userService.findAll();
    }

    @GetMapping("/findByPage")
    public PageInfo findByPage(int pageNum, int pageSize) {
    
    
        return userService.findByPage(pageNum, pageSize);
    }

}

验证

使用ApiFox调用分页接口,查询第1页的5条数据

image-20230624213245072

可以看到,后端也只是查到了5条数据,这其实是PageHelper在findAll方法的SQL调用前给它拼接了limit条件,所以只返回了我们需要的数据,而不是全部数据

image-20230624213207458

猜你喜欢

转载自blog.csdn.net/weixin_41405524/article/details/131367871