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. 【C#】【平时作业】习题-11-ADO.NET

    选择题 1.下列ASP.NET语句(B)正确地创建了一个与mySQL数据库和服务器的连接. A.SqlConnection con1 = new Connection("Data Sourc ...

  2. git学习之git reset命令

    Git版本恢复命令 reset命令有3种方式: git reset –mixed:此为默认方式,不带任何参数的git reset,即时这种方式,它回退到某个版本,只保留源码,回退commit和inde ...

  3. 一个GLSL Shader的格式化算法(LALR解析器)

    一个GLSL Shader的格式化算法(LALR解析器) 在进行OpenGL程序开发时,我需要自行解析`string`类型的Shader代码,抽取出里面的某些变量名和subroutine名. 由于找不 ...

  4. Qt编写嵌入式linux输入法/支持自定义词语和繁体/支持wayland和watson/纯QWidget/界面精美可换肤

    一.功能特点 纯QWidget编写,原创输入法机制,没有任何第三方动态库的依赖. 支持各种Qt版本,包括Qt4.Qt5.Qt6及后续版本. 支持各种编译器,包括mingw.msvc.gcc.clang ...

  5. Qt编写物联网管理平台38-多种数据库支持

    一.前言 本系统设计之初就要求支持多种不同的数据库,比如sqlite.mysql.postgres.sqlserver等,甚至包括国产数据库比如人大金仓kingbase等,(由于现在国产化的大力推进, ...

  6. Qt Creator 5.0 发布

    我们很高兴地宣布 Qt Creator 5.0 的发布! 正如4.15 发布博文中所宣布的,我们将切换到语义版本控制方案,因此这是 Qt Creator 很长一段时间以来的第一次主要版本更新!不过不要 ...

  7. Qt开源作品31-屏幕截图控件

    一.前言 屏幕截图控件在我的很多项目中都有用到,尤其是嵌入式的系统上的软件,因为在嵌入式系统中,基本上系统都很精简,甚至连UI都没有,开机之后直接运行的就是Qt程序,很多时候需要对软件进行截图保存下来 ...

  8. Many-shot Jailbreaking💘足够长的上下文长度有利于各种越狱?

    这篇文章虽然相较于上一篇图的对应有点迷,但是我感到了作者在强化学习与微调还有数学方面的深厚功底,我甚至感觉他的附录可以再发一篇文章了 这阶段的学习打开了我对越狱的思路~ 禁止盗用,侵权必究!!!欢迎大 ...

  9. Visual Studio2012编译C#项目时出错“LC.exe”已退出的解决方法

    症状: Visual Studio2012编译C#项目时出错"LC.exe"已退出,代码为 -1. 原因: 因为证书的原因,把项目中"properties"目录 ...

  10. JS利用浏览器进行语言识别

    JS利用浏览器进行语言识别 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...