limit m,nPageHelper、MyBatisPlus分页插件

001 || MybatisPlus分页插件

(1)引入maven依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.4</version>
</dependency>

(2)在MybatisPlusConfig中进行配置

package com.harley.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class MybatisPlusConfig { @Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 指定数据库类型
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
return interceptor;
}
}

(3)测试

@Test
void testPage(){
Page<User> page = new Page<>(1, 5);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println); }

(4)Service层

package com.harley.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.harley.entity.Account;
import java.util.List; /**
* <p>
* 需要同步元数据的表配置 服务类
* </p>
*
* @author harley
* @since 2024-12-17
*/
public interface AccountService extends IService<Account> { IPage<Account> getRecordPage(int currentPage, int pageSize, String keyword); }

(5)实现类

package com.harley.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.harley.entity.Account;
import com.harley.mapper.AccountMapper;
import com.harley.service.AccountService; /**
* <p>
* 需要同步元数据的表配置 服务实现类
* </p>
*
* @author harley
* @since 2024-12-17
*/
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService { @Autowired
private AccountMapper accountMapper; @Override
public IPage<Account> getRecordPage(int currentPage,int pageSize,String keyword){
// 创建Page对象, 传入当前页和每页记录数
Page<Account> page = new Page<>(currentPage, pageSize);
LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<>();
// 根据更新时间降序排列
lambdaQueryWrapper.orderByDesc(Account::getUpdateTime);
// 如果关键字非空,则进行模糊查询
if( keyword != null && !keyword.isEmpty()){
lambdaQueryWrapper.like(Account::getName,keyword)
.or()
.like(Account::getUsername,keyword);
} // 进行分页查询
return accountMapper.selectPage(page, lambdaQueryWrapper);
} }

(6)Controller层

package com.harley.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.harley.entity.Account;
import com.harley.mapper.AccountMapper;
import com.harley.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
*
* @author harley
* @since 2024-12-17
*/
@RestController
@RequestMapping("/account")
public class SyncTblConfigController { @Autowired
private AccountService accountService; @GetMapping("/getRecordPage")
public IPage<Account> getRecordPage(@RequestParam Integer currentPage,
@RequestParam Integer pageSize,
@RequestParam(value = "keyword", defaultValue = "", required = false) String keyword){ return accountService.getRecordPage(currentPage, pageSize, keyword);
} }

(7)vue页面

<template>
<div>
<div class="page-main">
<!-- 搜索框和按钮 -->
<div class="search-bar">
<el-input placeholder="请输入数据库名或表名关键字" v-model="query.keyword" style="width:500px;" clearable @input="debouncedFetchRecords">
<!-- <template #append>
<el-button type="primary" icon="el-icon-search" @click="fetchrecords">搜索</el-button>
</template> -->
</el-input>
<el-button type="success" style="margin-left:30px;" @click="showDialog('add',row=null)">新增</el-button>
</div>
</div>
<el-table :data="records" style="width: 100%">
<el-table-column prop="id" label="序号" width="auto"></el-table-column>
<el-table-column prop="databaseName" label="数据库" width="auto"></el-table-column>
<el-table-column prop="tableName" label="表名" width="400"></el-table-column>
<el-table-column prop="operator" label="操作人员">
<template slot-scope="scope">{{ scope.row.operator || 'N/A'}}</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间"></el-table-column>
<el-table-column prop="updateTime" label="更新时间"></el-table-column>
<el-table-column prop="owner" label="owner"></el-table-column>
<el-table-column label="操作" width="200">
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="showDialog('edit',scope.row)"><i class="el-icon-edit" style="font-size: 15px;"></i> 编辑</el-button>
<!-- <el-button size="mini" type="danger" @click="deleteRecord(scope.row.id)"><i class="el-icon-delete" style="font-size: 15px;"></i> 删除</el-button> -->
</template>
</el-table-column>
</el-table>
<!-- 分页控件 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="query.pageNum"
:page-size="query.pageSize"
:total="query.total"
layout="total, sizes, prev, pager, next, jumper"
:page-sizes="[5, 10]"
style="text-align: center;"
></el-pagination>
<!-- 新增/编辑对话框 -->
<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
<el-form :model="form" :rules="rules" ref="form" label-width="100px">
<el-form-item label="编号" prop="id">
<el-input v-model="form.id" disabled></el-input>
</el-form-item>
<el-form-item label="数据库" prop="databaseName">
<el-input v-model="form.databaseName"></el-input>
</el-form-item>
<el-form-item label="表名" prop="tableName">
<el-input v-model.number="form.tableName"></el-input>
</el-form-item>
<el-form-item label="操作人员" prop="operator">
<el-input v-model.number="form.operator"></el-input>
</el-form-item>
<el-form-item label="owner" prop="owner">
<el-input v-model.number="form.owner"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button> <!-- 点击取消按钮,遮罩层隐藏 -->
<el-button type="primary" @click="handleSubmit">确 定</el-button>
</span>
</el-dialog> </div> </template> <script>
import axios from 'axios';
import { debounce } from 'lodash'; export default {
name: 'SyncTblConfigPage',
data() {
return {
query: {
keyword: '',
pageNum: 0,
pageSize: 5,
total: 10,
},
tableData: [],
loading: false,
records: [],
editVDialogVisible: false,
selectedRecord: null,
dialogVisible: false, // 控制对话框的显示与隐藏,默认为隐藏
dialogTitle: '', // 对话框标题
form: {
id: null,
name: '',
username: '',
password: '',
comment: '',
},// 表单数据
rules: {
databaseName: [{ required: true, message: '数据库名不能为空', trigger: 'blur' }],
tableName: [{ required: true, message: '表名不能为空', trigger: 'blur' }],
operator: [{ required: false, message: '请输入操作人员', trigger: 'blur' }],
owner: [{ required: true, message: 'owner不能为空', trigger: 'blur' }],
}, // 表单验证规则
currentRow: null, // 当前编辑的行数据
};
},
created() {
this.fetchrecords();
this.debouncedFetchRecords = debounce(this.fetchrecords, 500);
this.$watch('query.keyword', (newVal) => {
if (!newVal) {
this.fetchrecords();
}else {
this.debouncedFetchRecords = debounce(this.fetchrecords, 500);
}
});
},
methods: {
async fetchrecords() {
await axios.get('/api/syncTblConfig/getRecordPage',{
params: {
currentPage: this.query.pageNum,
pageSize: this.query.pageSize,
keyword: this.query.keyword,
}
}).then(response => {
this.records = response.data.records.map(Record => ({
id: Record.id,
databaseName: Record.databaseName,
tableName: Record.tableName,
operator: Record.operator,
createTime: new Date(Record.createTime).toLocaleString(),
updateTime: new Date(Record.updateTime).toLocaleString(),
owner: Record.owner,
}));
this.query.total = response.data.total;
this.query.pageNum = response.data.current;
this.query.pageSize = response.data.size;
}).catch(error => {
console.error('There was an error fetching the records!', error);
}); },
showDialog(type, row = null) {
this.dialogVisible = true;
this.dialogTitle = type === 'add' ? '新增记录' : '编辑记录';
this.currentRow = row; if (type === 'add') {
this.$refs.form && this.$refs.form.resetFields();
} else if (row) {
this.form = { ...row }; // 使用展开运算符复制对象以避免引用问题
}
},
async deleteRecord(id){
try{
const response = await axios.get(`/api/Record/del?id=${id}`);
console.log('已删除: ' + response.data)
await this.fetchrecords();
}catch(error){
console.error('删除失败', error);
}
},
handleSubmit() {
if (this.dialogTitle === '新增记录') {
this.$refs.form.validate((valid) => {
if (valid) {
axios.post('/api/Record/addRecord', this.form)
.then(response => {
console.log('新增成功: ' + response.data);
this.$message({
message: '新增账号',
type: 'success'
});
this.dialogVisible = false;
this.records.push({ ...this.form });
this.fetchrecords();
})
.catch(error => {
console.error('新增账号失败', error);
this.$message({
message: '新增账号失败',
type: 'error'
});
});
} else {
console.log('表单验证失败!!');
return false;
}
}); } else if(this.dialogTitle === '编辑记录'){
this.$refs.form.validate((valid) => {
if (valid) {
axios.put(`/api/Record/updateRecord/${this.form.id}`, this.form)
.then(response => {
console.log('更新成功: ' + response.data);
this.$message({
message: response.data,
type: 'success'
});
this.dialogVisible = false;
const index = this.records.findIndex(Record => Record.id === this.form.id);
if (index !== -1) {
this.$set(this.records,index, { ...this.form });
}
this.fetchrecords();
})
.catch(error => {
console.error('更新失败', error);
this.$message({
message: '更新失败',
type: 'error'
});
});
} else {
console.log('表单验证失败!!');
return false;
}
});
}
},
handleSizeChange(newSize) {
console.log(`每页 ${newSize} 条`);
this.query.pageSize = newSize;
this.fetchrecords();
},
handleCurrentChange(newPage) {
console.log(`当前页: ${newPage}`);
this.query.pageNum = newPage;
this.fetchrecords();
},
debouncedFetchRecords: debounce(function(){this.fetchRecords()}, 500).bind(this),
}
}
</script>
<style scoped> </style>

— 业精于勤荒于嬉,行成于思毁于随 —

MybatisPlus - [04] 分页的更多相关文章

  1. Mybatis-Plus的分页插件

    使用的是:Mybatis-Plus的分页插件https://baomidou.gitee.io/mybatis-plus-doc/#/?id=%E7%AE%80%E4%BB%8B 1.Mapper.j ...

  2. 【mybatis-plus】分页、逻辑删除

    通过mybatis-plus实现分页,也是很简单,插件大法. 一.分页 1.配置分页插件 把分页的插件也配置到统一的配置类里: @Configuration // 配置扫描mapper的路径 @Map ...

  3. MybatisPlus联合分页查询

    跟单表分页查询差不多 1.编写查询语句 public interface QuestionMapper extends BaseMapper<Question> { @Select(&qu ...

  4. SpringBoot使用Mybatis-plus及分页功能的细节部分

    pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  5. MyBatisPlus实现分页和查询操作就这么简单

    <SpringBoot整合MybatisPlus基本的增删改查,保姆级教程>在这篇文章中,我们详细介绍了分页的具体实现方法.但是,在日常的开发中还需要搜索功能的.下面让我们一起动起手来,实 ...

  6. 实验:spring-boot整合mybatis-plus实现分页查询的功能

    1.建立基于sping-boot的javaweb工程(java1.8) 按结构建立包 2.POM.XML添加支持mybatis-plus,sql,lombok <!--mybatis-plus的 ...

  7. Mybatis-plus使用分页进行分页查询

    首先先配置配置文件 @Configuration public class MybatisPlusConfig { @Bean public PaginationInterceptor paginat ...

  8. MyBatis-Plus 分页插件过时

    引用:https://blog.csdn.net/zyw562123314/article/details/108903456//分页插件老版本过时 旧版本配置 @Bean public Pagina ...

  9. 小书MybatisPlus第4篇-表格分页与下拉分页查询

    本文为mybatis系列文档的第4篇,前三篇请访问下面的网址. 小书MybatisPlus第1篇-整合SpringBoot快速开始增删改查 小书MybatisPlus第2篇-条件构造器的应用及总结 小 ...

  10. 若依3.6.0使用Mybatis-plus分页失效以及完美替换Pagehelper

    一.前言 小编最近在经历后端框架的迁移,虽然不是小编来做,但是有个分页的情况让小编和一个同事去搞. 说一下小编这边的需求: 原来框架使用Mybatis-plus进行分页,要更换的新框架若依是使用Pag ...

随机推荐

  1. 【巧用set实现对有序数组O(logn)时间复杂度增、删、查、改、二分操作】codeforces 1041 C. Coffee Break

    题意 第一行输入三个整数 \(n,m,d(1 \leq n \leq 2 * 10^5, n \leq m \leq 10^9, 1 \leq d \leq n)\),第二行输入 \(n\) 个整数, ...

  2. codeforces1849 D. Array Painting

    题目链接 https://codeforces.com/problemset/problem/1849/D 题意 输入 \(n(1 \leq n \leq 2e5)\) 和长为 \(n\) 的数组 \ ...

  3. Idea 避免import *

    File -> setting -> Editor -> Code Style -> Java -> Imports

  4. 基于C#实现串口通信Demo

    原文链接:基于C#实现串口通信Demo

  5. OpenGL ES 3.x游戏开发(上+下卷)书籍的电子版+源程序

    直接附上电子书以及源代码下载链接:https://pan.baidu.com/s/1G10hw5aIi-Bc2LyktwKrdg

  6. Linux 终端

    在 Linux 系统中,终端设备通常分为主设备和从设备.这是一种特殊的设备对的概念,其中: 主设备: 主设备也称为 "master device". 它是终端设备的控制端,用于与用 ...

  7. 基于STC8G1K08的CH549单键进入USB下载模式实验

    一.实验原因 CH552或CH549进入USB下载,通常需要两个按键,一个控制电源的通断,一个通过串联电阻(一头接VCC或V33)冷启动时抬高UDP电平.时序上是这样的:断电--按下接UDP的轻触开关 ...

  8. 《CUDA编程:基础与实践》读书笔记(4):CUDA流

    1. CUDA流 一个CUDA流指的是由主机发出的在一个设备中执行的CUDA操作序列.除主机端发出的流之外,还有设备端发出的流,但本文不考虑后者.一个CUDA流中的各个操作按照主机发布的次序执行:但来 ...

  9. Linux性能优化-网络性能优化思路

    目录 确定优化目标 网络性能工具 网络性能优化 应用程序 套接字 传输层 网络层 链路层 确定优化目标优化前,首先要确定观察到的网络性能指标,要达到多少才合适?虽然网络性能优化的整体目标,是降低网络延 ...

  10. 轮播图,swiper使用

    背景: 最近接到一个需求,重写首页,需要用到轮播图. 但是轮播图只用两张图,此为前提. 本想直接用ElementUI的走马灯,但是只用两张图的情况下,走马灯不能循环播放,只能来回播放,公司的UI小姐姐 ...