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. 中电金信:技术实践|Flink维度表关联方案解析

    ​ 导语:Flink是一个对有界和无界数据流进行状态计算的分布式处理引擎和框架,主要用来处理流式数据.它既可以处理有界的批量数据集,也可以处理无界的实时流数据,为批处理和流处理提供了统一编程模型. 维 ...

  2. kubectl按pod创建时间排序获取列表 _

    按时间排序,可以更快地找到最近更新的pod 基于当前ns 1 kubectl get pods --sort-by=.metadata.creationTimestamp BASH 基于整个集群 1 ...

  3. error C2065: “CV_DATA_AS_ROW”: 未声明的标识符

    ce_dect\main_face.cpp(117): error C2065: "CV_DATA_AS_ROW": 未声明的标识符将 "CV_PCA_DATA_AS_R ...

  4. 《AutoCAD2020中文版基础教程》和《从零开始—AutoCAD 2020中文版基础教程》配套资源下载

    <AutoCAD2020中文版基础教程>作者:姜春峰//武小紅//魏春雪中国青年出版社配套资源链接:https://pan.baidu.com/s/1kPGNKZEw2kOTGqZyXjp ...

  5. 如何通过C#修改Windows操作系统时间

    C#的System.DateTime类提供了对日期时间的封装,用它进行时间的转换和处理很方便,但是我没有在其中找到任何可以用来修改系统时间的成员.用过VC.VB等的朋友可能知道,我们可以调用Win32 ...

  6. [转]WorldWind开发中WorldWindowGLCanvas .setPreferredSize()函数找不到

    值高温假期,无意翻到了csdn中三维GIS开发的专栏,讲的是worldwind Java三维GIS系统开发的东西,十分感兴趣.恰巧要求的环境已经存在,直接耍起来.将最新的Worldwind和JOGL下 ...

  7. 彻底讲透Spring AOP动态代理,原理源码深度剖析!

    1.AOP:[动态代理]定义 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式: 2.基于注解aop的开发流程 1.导入aop模块:Spring AOP:(spring-asp ...

  8. ConcurrentLinkedQueue深度源码剖析

    在Java的并发包中,存在着许多高效的并发工具类,它优于synchronized关键字,在JDK中提供了一个ConcurrentLinkedQueue工具类实现了高效的并发读写工具类,该工具类具有很高 ...

  9. CyclicBarrier底层实现和原理

    1.CyclicBarrier 字面意思是可循环(Cyclic)使用的屏障(Barrier).它要做的事情是让一组线程到达一个屏障(同步点)时被阻塞,直到最后一个线程到达屏障时候,屏障才会开门.所有被 ...

  10. java代码之美(2)

    guava 复写Object常用方法 Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方 ...