MybatisPlus与前端分页工具结合实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MybatisPlus与前端分页工具结合实现相关的知识,希望对你有一定的参考价值。

参考技术A 虽然MybatisPlus提供了PaginationInnerInterceptor插件用来分页,并且该插件使用起来也还不错,但是我们开发项目的时候总是希望前后端搭配干活,实现一些好用的功能。

比如说前端表单点击表头排序,这个功能我们就可以结合分页插件完成。而且我们现在很多时候会开发多端项目,在不同前端使用不同组件适配后端接口的时候,总可能遇到命名方式不一致的问题,比如A前端框架中当前页叫currPage,B框架中叫page等情况。基于这样的实际情况,我们需要对项目中MybatisPlus的分页进行一定程度的封装,让它能满足我们不同情况下的实际需要。

首先是分页插件的配置

配置好分页插件以后MybatisPlus就支持分页了,可以使用service的page方法或者mapper的selectPage方法进行分页。这两个方法都需要传入com.baomidou.mybatisplus.extension.plugins.pagination.Page对象,这个对象也就是实际用来分页的参数对象了。我们可以在这个对象中设置分页的页数,每页的数据数量,同时也可以设置排序的字段、排序的方式。但是排序字段是直接通过字符串连接的方式填写在sql中的,所以是存在sql注入的风险的,所以我们需要个过滤SQL注入工具类,我参考了JeecgBoot中的工具类,稍作修改

com.baomidou.mybatisplus.extension.plugins.pagination.Page这个分页工具只是提供了分页的功能,但是并不能很方便的直接拿来使用,所以我封装了一个工具类,用来通过我们写好的配置从参数中获取分页需要的信息以及配合前端Table排序的参数信息,并且过滤了SQL注入

相同的,不同的Table框架中接收的数据格式也有一些差别,我们分页方法返回的com.baomidou.mybatisplus.core.metadata.IPage也不能满足我们的格式要求。所以根据实际情况封装一个工具类,用来返回我们需要的数据格式

最后分页调用的时候就变得简单了

分页插件:PageHelper+BootStrap+Vue+axios实现分页功能

本教程需要有MyBatisPlus基础,学习MyBatisPlus请参考
SpringBoot第 14 讲:SpringBoot+MyBatisPlus

案例效果

技术栈

后端技术:SpringBoot2.7.9、MyBatisPlus3.5.1、MySQL8
前端技术:Vue2.5.16+axios、BootStrap3.3.7

一、后端开发

1.1、配置MyBatisPlus

1.1.1、在pom.xml中添加依赖

		<!-- Spring&SpringMVC -->
        <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.5.1</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <!-- mysql-connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>

1.1.2、在application.yml中配置数据源

server:
  port: 8070
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.01:3306/test_plus?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
    username: root
    password: Aa123123.
mybatis-plus:
  type-aliases-package: demo.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      table-prefix: t_
      id-type: auto
  mapper-locations: classpath:mappers/*.xml

1.1.3、在启动类中配置分页插件

package demo;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SpringBootApplication
@Configuration
@MapperScan("demo.mapper")
public class Demo 

    /** 配置分页插件*/
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() 
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    

    public static void main(String[] args) 
        SpringApplication.run(Demo.class);
    

1.2、后台开发

1.2.1、SQL脚本

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_article
-- ----------------------------
DROP TABLE IF EXISTS `t_article`;
CREATE TABLE `t_article` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `logo` varchar(255) DEFAULT NULL,
  `descn` varchar(160) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `cid` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1630090627736408069 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_article
-- ----------------------------
BEGIN;
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1, '扬子xx', NULL, 'eeeeeeee', '2023-01-02 00:00:00', 2);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090618022400001, '扬子晚报1', NULL, 'dddsfjslfjalskd', '2023-01-03 00:00:00', 2);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090625282740226, '扬子晚报2', NULL, 'dddsfjslfjalskd', '2023-01-04 00:00:00', 2);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090625865748482, '扬子晚报3', NULL, 'dddsfjslfjalskd', '2023-01-05 00:00:00', 1);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090626520059905, '扬子晚报4', NULL, 'dddsfjslfjalskd', '2023-01-06 00:00:00', 2);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090627165982721, '扬子晚报5', NULL, 'dddsfjslfjalskd', '2023-01-07 00:00:00', 1);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090627736408066, '扬子晚报6', NULL, 'dddsfjslfjalskd', '2023-01-08 00:00:00', 1);
INSERT INTO `t_article` (`id`, `title`, `logo`, `descn`, `create_time`, `cid`) VALUES (1630090627736408068, 'qqq1w', 'kdsjlsfjieosjfiosjdfo', 'eeeee', '2023-02-03 00:00:00', 2);
COMMIT;

-- ----------------------------
-- Table structure for t_channel
-- ----------------------------
DROP TABLE IF EXISTS `t_channel`;
CREATE TABLE `t_channel` (
  `id` bigint(20) NOT NULL,
  `channel_name` varchar(50) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_channel
-- ----------------------------
BEGIN;
INSERT INTO `t_channel` (`id`, `channel_name`, `create_time`) VALUES (1, '头条', '2023-02-27 17:27:14');
INSERT INTO `t_channel` (`id`, `channel_name`, `create_time`) VALUES (2, '头七', '2023-02-27 17:27:14');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

1.2.2、实体Article

package demo.entity;

import lombok.Data;

@Data
public class Article 
    private Long id;
    private String title;
    private String logo;
    private String descn;
    private String createTime;
    private Long cid;

1.2.3、ArticleMapper.java

package demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import demo.entity.Article;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface ArticleMapper extends BaseMapper<Article> 

    Page<Article> selectByPage(Page<Article> page, @Param("title") String title);

1.2.4、ArticleMapper.xml

<?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="demo.mapper.ArticleMapper">
    <select id="selectByPage" resultType="Article">
        select * from t_article where title like '%$title%'
    </select>
</mapper>

1.2.5、ArticleController

package demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import demo.entity.Article;
import demo.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class ArticleController 

    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping("/list")
    public Page<Article> findAll(Long pageIndex, Long pageSize)
        Page<Article> page = articleMapper.selectPage(new Page(pageIndex, pageSize), null);
        return page;
    

    @GetMapping("/list_custom")
    public Page<Article> customFindAll(Long pageIndex, Long pageSize, String title)
        Page<Article> page = articleMapper.selectByPage(new Page(pageIndex, pageSize), title);
        return page;
    

二、前端开发

2.1、html代码

	<div class="container" id="app">
        <table class="table table-striped">
            <caption>文章列表</caption>
            <thead>
            <tr>
                <th align="center">编号</th>
                <th align="center">标题</th>
                <th align="center">描述</th>
                <th align="center">发布时间</th>
                <th align="center">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="art in articleList">
                <td>art.id</td>
                <td>art.title</td>
                <td>art.descn</td>
                <td>art.createTime</td>
                <td align="center">
                    <button class="btn btn-link" style="margin-right: 10px;">修改</button>
                    <button class="btn btn-link">删除</button>
                </td>
            </tr>
            </tbody>
        </table>
        <ul class="pagination" v-for="p in pageCnt">
            <li v-if="p == pageIndex" class="active">以上是关于MybatisPlus与前端分页工具结合实现的主要内容,如果未能解决你的问题,请参考以下文章

mybatis-plus分页查询

全栈之前端编程Javaweb使用thymeleaf局部刷新结合Layui插件实现Html分页

全栈之前端编程Javaweb使用thymeleaf局部刷新结合Layui插件实现Html分页

全栈之前端编程Javaweb使用thymeleaf局部刷新结合Layui插件实现Html分页

Vue+SpringBoot 前后端分离实战(mybatisplus多表分页查询+博客显示)

pagerHelper与mybatisPlus分页冲突问题分析