spring boot加mybatis puls实现,在新增/修改时,对某些字段进行处理,使用的@TableField()

1.先说场景,在对mysql数据库表数据插入或者更新时都得记录时间和用户id

传统实现有点繁琐,这里还可以封装一下公共方法。

2.解决方法:

2.1:使用aop切面编程(记录一下,有时间再攻克)。

2.2:使用@TableField()注解。

3.我使用的@TableField 注解实现,因为没有很多的业务处理,单纯的记录一下,以下是具体实现

复制代码
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 在插入时自动填充 create_time 和 update_time 字段
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", String.class, BaseUtlis.getCurrentUser().getId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 在更新时自动填充 update_time 字段
        this.strictUpdateFill(metaObject, "updateTime",Date.class, new Date());
        this.strictInsertFill(metaObject, "updateBy", String.class, BaseUtlis.getCurrentUser().getId());
    }
}

注: 字段需要跟实体类对应起来,我项目架构是使用了驼峰命名使用下划线后字母大写。BaseUtlis.getCurrentUser().getId(),这个是我封装的一个获取当前登录用户的方法。

参数解析:

this.strictUpdateFill(metaObject, "updateTime",Date.class, new Date());

metaObject:对象

updateTime:实体类目标字段

Date.class:数据类型

new Date():具体值

4.yml配置

复制代码
mybatis-plus:
  global-config:
    db-config:
      meta-object-handler: com.zuodou.mymeta.MyMetaObjectHandler

5.在对应实体类的字段上加

复制代码
@TableField(fill = FieldFill.UPDATE)

或者

复制代码
@TableField(fill = FieldFill.INSERT)

6.补充缺陷

直接在controllerdi调用根据id修改方法 或者 update 批量根据id修改, 会不触发自动填充

解决使用update,条件传入id或者在service调用,而updateBatchById就需要手动传了。

至于为什么在service调用updateById就能触发

在 MyBatis Plus 中,通常通过继承 ServiceImpl 类来实现 Service 层的操作。这个类提供了一些默认的 CRUD(增删改查)方法,并且默认情况下会使用 MyBatis Plus 的内置功能,比如自动填充。

当你在自己的 Service 类中继承了 ServiceImpl 并且指定了泛型类型,比如 YourService extends ServiceImpl<YourMapper, YourEntity>,这样就将 YourService 和 YourEntity 关联起来了。

MyBatis Plus 的 ServiceImpl 已经预先实现了一些常见的操作方法,其中包括了自动填充的支持。在这个类中,如果你调用了 updateById 方法,它内部会调用 MyBatis Plus 的自动填充逻辑,以便在更新数据时触发自动填充。

当然,前提是你需要做以下几件事情:

1.确保你的实体类中的字段有正确地标注了自动填充的注解,比如使用了 @TableField 注解并设置了相应的 fill 属性。

2.确保你已经正确配置了 MetaObjectHandler,并且这个配置被正确地注册到了 Spring 容器中。这样 MyBatis Plus 才能正确地使用自动填充功能。

因此,当你在自定义的 Service 类中继承了 ServiceImpl,就相当于在你的 Service 类中内置了 MyBatis Plus 提供的默认实现,包括自动填充的支持。这样,在调用 updateById 等方法时,会自动触发 MyBatis Plus 的自动填充逻辑。

(侵权联系删除)

相关推荐
nbsaas-boot18 小时前
Drools 规则引擎实战:原理、规则语法、数据库动态规则与企业级玩法
java·数据库·python
承渊政道18 小时前
【MySQL数据库学习】(MySQL数据库基础)
数据库·学习·mysql·ubuntu·bash·数据库架构·数据库系统
0pen118 小时前
android-sqlite3:从官方 SQLite 源码自动构建 Android 可用的 sqlite3
android·数据库·sqlite
六月雨滴18 小时前
Oracle RMAN 恢复场景全解
数据库·oracle·dba
韩小兔修媛史18 小时前
SpringBoot面试八股文(持续更新)
spring boot·后端·面试
憧憬成为java架构高手的小白18 小时前
苍穹外卖--day11数据统计-图形报表(管理端)
java·spring boot·echarts
IvorySQL18 小时前
PostgreSQL 18.4、17.10、16.14、15.18、14.23 版本正式发布
数据库·postgresql·区块链
JAVA面经实录91718 小时前
完整版Spring全家桶学习体系
java·spring boot·spring·面试
YOU OU18 小时前
MyBatis-Plus 使用
mybatis
weixin_5206498718 小时前
C#队列Queue详解
开发语言·数据库·c#