MyBatis-Plus 自动填充:优雅实现创建/更新时间自动更新!

devtools/2025/3/30 3:19:07/

在这里插入图片描述

目录

    • 一、什么是 MyBatis-Plus 自动填充? 🤔
    • 二、自动填充的原理 ⚙️
    • 三、实际例子:创建时间和更新时间字段自动填充 ⏰
    • 四、注意事项 ⚠️
    • 五、总结 🎉

🌟我的其他文章也讲解的比较有趣😁,如果喜欢博主的讲解方式,可以多多支持一下,感谢🤗!

🌟了解 MyBatis-Plus 逻辑删除请看: MyBatis-Plus 逻辑删除:让数据“消失”却不真正删除的秘密!

其他优质专栏: 【🎇SpringBoot】【🎉多线程】【🎨Redis】【✨设计模式专栏(已完结)】…等

如果喜欢作者的讲解方式,可以点赞收藏加关注,你的支持就是我的动力
✨更多文章请看个人主页: 码熔burning

一、什么是 MyBatis-Plus 自动填充? 🤔

MyBatis-Plus 自动填充是指在执行 insertupdate 操作时,自动为某些字段设置值,而无需手动在代码中进行赋值。 这对于一些通用字段(如创建时间、更新时间、创建人、修改人等)非常有用,可以减少重复代码,提高开发效率,并保证数据的一致性。 🚀

二、自动填充的原理 ⚙️

MyBatis-Plus 通过拦截器机制,在执行 SQL 语句之前,根据配置的规则,自动为指定的字段设置值。

自动填充的实现步骤 📝

  1. 定义实体类字段: 在实体类中定义需要自动填充的字段,并使用 MyBatis-Plus 提供的注解进行标记。
  2. 编写填充处理器: 创建一个类,实现 MyBatis-Plus 提供的 MetaObjectHandler 接口,并在该类中编写填充逻辑。
  3. 配置 MyBatis-PlusMyBatis-Plus 的配置中,注册填充处理器。

三、实际例子:创建时间和更新时间字段自动填充 ⏰

假设我们有一个 User 实体类,其中包含 createTimeupdateTime 两个字段,分别表示创建时间和更新时间。

1. 定义实体类字段

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;import java.io.Serializable;
import java.time.LocalDateTime;@Data
@EqualsAndHashCode(callSuper = false)
@TableName("user")
public class User extends Model<User> {private static final long serialVersionUID = 1L;@TableIdprivate Long id;private String name;private Integer age;private String email;@TableField(fill = FieldFill.INSERT) // 插入时填充字段private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE) // 插入和更新时填充字段private LocalDateTime updateTime;@Overrideprotected Serializable pkVal() {return this.id;}}

解释:

  • @TableField(fill = FieldFill.INSERT):表示该字段在执行 insert 操作时进行填充。
  • @TableField(fill = FieldFill.INSERT_UPDATE):表示该字段在执行 insertupdate 操作时进行填充。
  • LocalDateTime:这里使用 LocalDateTime 作为时间类型,也可以使用 DateInstant 等。

2. 编写填充处理器

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;@Slf4j
@Component // 不要忘记加Component注解
public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("start insert fill ....");this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());}@Overridepublic void updateFill(MetaObject metaObject) {log.info("start update fill ....");this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)}
}

解释:

  • MyMetaObjectHandler 类实现了 MetaObjectHandler 接口。
  • insertFill 方法:在执行 insert 操作时,会调用该方法。 我们在这里为 createTimeupdateTime 字段设置当前时间。
  • updateFill 方法:在执行 update 操作时,会调用该方法。 我们在这里为 updateTime 字段设置当前时间。
  • strictInsertFillstrictUpdateFill 方法:是 MyBatis-Plus 3.3.0 版本之后推荐使用的填充方法,更加安全和严格。 它们会检查字段是否存在,类型是否匹配,以及是否已经有值,避免覆盖已有值。
  • @Component:将该类注册为 Spring Bean,以便 MyBatis-Plus 可以自动发现它。

3. 配置 MyBatis-Plus

在 Spring Boot 的配置文件(例如 application.ymlapplication.properties)中,不需要显式配置 MyBatis-Plus 的自动填充功能。 只要你的填充处理器类被 Spring 管理(例如通过 @Component 注解),MyBatis-Plus 就会自动识别并使用它。 🎉

使用示例 🚀

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testInsert() {User user = new User();user.setName("testUser");user.setAge(25);user.setEmail("test@example.com");int result = userMapper.insert(user);System.out.println("影响行数:" + result);System.out.println("插入后的用户ID:" + user.getId());System.out.println("插入后的用户创建时间:" + user.getCreateTime());System.out.println("插入后的用户更新时间:" + user.getUpdateTime());}@Testpublic void testUpdate() {User user = userMapper.selectById(1L); // 假设ID为1的用户存在user.setName("updatedUser");int result = userMapper.updateById(user);System.out.println("影响行数:" + result);System.out.println("更新后的用户更新时间:" + user.getUpdateTime());}
}

解释:

  • testInsert 方法中,我们创建了一个 User 对象,并设置了 nameageemail 字段。 createTimeupdateTime 字段没有手动设置。
  • 执行 userMapper.insert(user) 后,MyBatis-Plus 会自动调用 MyMetaObjectHandlerinsertFill 方法,为 createTimeupdateTime 字段设置当前时间。
  • testUpdate 方法中,我们先查询出一个 User 对象,然后修改了 name 字段。 updateTime 字段没有手动设置。
  • 执行 userMapper.updateById(user) 后,MyBatis-Plus 会自动调用 MyMetaObjectHandlerupdateFill 方法,为 updateTime 字段设置当前时间。

四、注意事项 ⚠️

  • 确保你的填充处理器类被 Spring 管理(例如通过 @Component 注解)。
  • 使用 strictInsertFillstrictUpdateFill 方法可以避免覆盖已有值。
  • 如果你的字段类型不是 LocalDateTime,需要根据实际类型进行调整。
  • 如果你的字段名不是 createTimeupdateTime,需要在填充处理器中修改字段名。
  • 如果你的数据库字段类型是 TIMESTAMP,建议使用 LocalDateTimeInstant 作为 Java 类型,并配置相应的类型处理器。
  • 如果你的数据库字段类型是 DATE,建议使用 LocalDate 作为 Java 类型。

五、总结 🎉

MyBatis-Plus 的自动填充功能可以极大地简化开发,提高效率,并保证数据的一致性。 通过定义实体类字段、编写填充处理器和配置 MyBatis-Plus,可以轻松实现创建时间和更新时间字段的自动填充。 希望篇文章能够帮助你理解和使用 MyBatis-Plus 的自动填充功能。 🥳


http://www.ppmy.cn/devtools/171619.html

相关文章

数据库基础知识点(系列五)

创建表&#xff0c;设置约束&#xff0c;修改表&#xff0c;删除表&#xff0c;表中数据的操作(insert,修改&#xff0c;删除) 1&#xff0e;在第5章习题创建的 “仓库库存”数据库中完成下列操作。 (1)创建“商品”表&#xff0c;表结构如表6-4&#xff1a; 表6-4 “goods”…

【transformer理论+实战(三)】必要的 Pytorch 知识

【Transformer理论实战&#xff08;三&#xff09;】必要的 Pytorch 知识 【Transformer理论实战&#xff08;二&#xff09;】Lora本地微调实战 --deepseek-r1蒸馏模型 【Transformer理论实战&#xff08;一&#xff09;】Transformer & LLaMA & Lora介绍 文章目录 Py…

Keil(ARMCC)编译改为Cmake(GNU)编译

1. 环境介绍&#xff1a; 某款ARM-M4芯片&#xff08;应该芯片通用&#xff09;cmkeGNUNinja&#xff08;CLion&#xff09; 2. 必备&#xff1a; 芯片启动文件 startup_xxxx.s链接文件 xxxx_flash.ldCMakeLists.txt 3. 具体修改步骤 第一步&#xff1a;观察启动文件…

Xenium | 细胞邻域(Cellular Neighborhood)分析(fixed k-nearest neighbor)

CN分析概念最早来源于空间单细胞蛋白组Codex文章&#xff0c;Coordinated Cellular Neighborhoods Orchestrate Antitumoral Immunity at the Colorectal Cancer Invasive Front。 定义 Cell Neighborhood&#xff08;细胞邻域&#xff09;指骨髓微环境中空间上邻近的细胞群体…

【Python-OpenCV】手势控制贪吃蛇

用手势玩转经典游戏&#xff1a;打造一个手势控制的贪吃蛇 你是否曾经想过&#xff0c;如果能用手势来控制游戏会是什么体验&#xff1f;今天&#xff0c;我要向大家介绍一个有趣的项目——手势控制贪吃蛇游戏。这个项目结合了计算机视觉和经典游戏&#xff0c;让你可以通过简单…

关于服务器只能访问localhost:8111地址,局域网不能访问的问题

一、问题来源&#xff1a; 服务器是使用的阿里云的服务器&#xff0c;服务器端的8111端口没有设置任何别的限制&#xff0c;但是在阿里云服务器端并没有设置相应的tcp连接8111端口。 二、解决办法&#xff1a; 1、使用阿里云初始化好的端口&#xff1b;2、配置新的阿里云端口…

如何监控 SQL Server

监控 SQL Server 对于维护数据库性能、确保数据可用性和最大限度地减少停机时间至关重要。随着企业越来越依赖数据驱动的决策&#xff0c;高效的SQL Server监控策略能显著提升组织生产力和用户满意度。 为什么要监控 SQL Server SQL Server 是许多关键应用程序的支柱&#xf…

fileinclude

##解题思路 场景首页没有什么提示&#xff0c;只有个flag在flag.php中&#xff0c;而且需要更改language&#xff0c;还有个index.php的路径&#xff0c;先记住它 习惯性查看源代码&#xff0c;得到了题目真正的内容&#xff0c;关键在于lan变量读取我们传入的Cookie值中的lang…