MyBatis-Plus 分页、条件构造器、自动填充、逻辑删除 完整课堂笔记

MyBatis-Plus 分页、条件构造器、自动填充、逻辑删除 完整课堂笔记

课次25:Lambda条件构造器 + 分页插件

一、教学目标

  1. 使用 LambdaQueryWrapper 安全构建查询条件,避免硬编码字段名
  2. 配置MyBatis-Plus分页插件,实现带排序的新闻分页查询

二、核心知识点

  1. LambdaQueryWrapper:类型安全条件构造器,通过实体方法引用写字段,编译期校验,防止字段名拼写错误
  2. 分页插件 PaginationInnerInterceptor:自动拦截SQL,拼接LIMIT分页语句,同时自动统计总记录数
  3. Page对象:封装分页参数(当前页码、每页条数)与分页结果(总条数、当前页数据)

三、完整操作步骤

1. 创建分页配置类 MyBatisPlusConfig

在包 com.weitoutiao.config 下新建配置类,注册分页拦截器

package com.weitoutiao.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 mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 指定MySQL数据库分页
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 页码溢出处理:超出最大页返回空数据
        paginationInterceptor.setOverflow(false);
        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }
}

2. 编写News业务层(MyBatis-Plus标准Service结构)

1)NewsService 接口,继承MyBatis-Plus内置业务接口

package com.weitoutiao.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.weitoutiao.entity.News;

public interface NewsService extends IService<News> {}

2)NewsServiceImpl 实现类,添加@Service交给Spring管理

package com.weitoutiao.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weitoutiao.entity.News;
import com.weitoutiao.mapper.NewsMapper;
import com.weitoutiao.service.NewsService;
import org.springframework.stereotype.Service;

@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {}

3. 分页测试代码(testSelect.java)

import com.baomidou.mybatisplus.core.metadata.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.weitoutiao.entity.News;
import com.weitoutiao.service.NewsService;

@SpringBootTest
class NewsServiceTest {
    @Autowired
    private NewsService newsService;

    @Test
    void testPage() {
        // 分页参数:第1页,每页5条
        Page<News> page = new Page<>(1, 5);
        // 构建条件:按发布时间倒序
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(News::getPublishTime);
        // 执行分页查询
        Page<News> result = newsService.page(page, wrapper);
        System.out.println("总记录数:" + result.getTotal());
        System.out.println("当前页数据:" + result.getRecords());
    }
}

代码爆红处理:鼠标悬浮报错处,一键导入对应依赖类

4. 数据库字段报错修复

运行测试会因缺少逻辑删除、自动填充字段抛出异常,执行两条SQL补充字段:

  1. 添加逻辑删除字段 deleted
ALTER TABLE `news` ADD COLUMN `deleted` TINYINT DEFAULT 0 COMMENT '逻辑删除(0未删除,1已删除)';
  1. 添加自动更新时间字段 update_time
ALTER TABLE `news` 
ADD COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间';

执行完成刷新表结构,再次运行测试即可正常打印分页数据。


课次26:自动填充 & 逻辑删除

一、教学目标

  1. 配置字段自动填充,自动生成创建时间、更新时间
  2. 掌握逻辑删除功能,实现数据软删除,保留数据库原始数据

二、核心知识点

  1. MetaObjectHandler:MyBatis-Plus字段填充处理器,新增/修改时自动赋值时间
  2. @TableField(fill = FillType.xxx):标记实体字段填充时机(INSERT/UPDATE/INSERT_UPDATE)
  3. 逻辑删除:不执行DELETE语句,通过deleted字段标记数据状态(0正常、1已删);所有查询/更新自动过滤已删除数据

三、完整操作步骤

1. 创建自动填充处理器 MyMetaObjectHandler

com.weitoutiao.config 新建类,添加@Component注入Spring容器

package com.weitoutiao.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    // 新增时填充创建时间、更新时间
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
    // 修改时仅更新更新时间
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}

配套实体News中 createTimeupdateTime 字段需添加填充注解

2. 逻辑删除功能测试(testSelect.java)

import com.weitoutiao.entity.News;
import com.weitoutiao.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class NewsMapperTest {
    @Autowired
    private NewsMapper newsMapper;

    @Test
    void testDelete() {
        int rows = newsMapper.deleteById(1);
        System.out.println("删除条数:" + rows);
        // 底层SQL自动转为UPDATE,而非DELETE:UPDATE news SET deleted=1 WHERE id=1
    }
}

3. 逻辑删除底层SQL变化

操作 原生SQL变化
新增 无变化,正常INSERT
删除 转换UPDATE,设置deleted=1
查询/修改 自动拼接 WHERE deleted=0,过滤已删除数据
示例:
  • 查询:SELECT * FROM news WHERE deleted=0
  • 删除:UPDATE news SET deleted=1 WHERE id=1 AND deleted=0

四、业务场景说明

企业项目几乎不使用物理删除(直接DELETE),原因:

  1. 误删除数据无法恢复,丢失业务历史记录
  2. 逻辑删除仅标记状态,数据永久留存,支持数据溯源、报表统计、恢复操作

四、两节课完整项目目录结构

com.weitoutiao
├── config                # 配置类包
│   ├── MyBatisPlusConfig.java    # 分页插件配置
│   └── MyMetaObjectHandler.java  # 时间自动填充处理器
├── entity
│   └── News.java         # 新闻实体(含createTime/updateTime/deleted字段)
├── mapper
│   └── NewsMapper.java   # Mapper接口,继承BaseMapper
├── service
│   ├── NewsService.java  # 业务接口
│   └── impl
│       └── NewsServiceImpl.java # 业务实现类
test/java/com/weitoutiao
└── testSelect.java       # 分页、逻辑删除单元测试

五、常见报错解决汇总

  1. 无法自动装配,找不到NewsService Bean
    • 确认实现类 NewsServiceImpl@Service
    • 启动类添加 @MapperScan("com.weitoutiao.mapper")
    • 清理IDEA缓存、Maven clean后重启项目
  2. 分页查询 getTotal() 总条数为0
    • 未创建 MyBatisPlusConfig 分页配置类,分页插件未注册
  3. 运行测试提示缺少deleted/update_time字段
    • 执行课堂提供的两条ALTER TABLE语句补充数据库字段
  4. 新增数据createTime为空
    • 检查 MyMetaObjectHandler 是否添加@Component
    • 实体对应字段添加 @TableField(fill = FieldFill.INSERT)
posted @ 2026-06-17 09:44  橙糯CiiiiiX  阅读(17)  评论(0)    收藏  举报