Mybtisplus对时间字段进行自动填充

一、引入依赖

XML 复制代码
 <!--        mybatis-plus-boot-starter-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

二、配置类

这里我主要对字段createTime和updateTime进行自动填充,你们可以修改为自己对应的字段即可。

java 复制代码
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
    }
}

三、使用填充功能

在需要填充的字段上加入 @TableField(fill = FieldFill.INSERT)或者 @TableField(fill = FieldFill.UPDATE),当执行SQL语句时就会拦截语句随后对SQL语句添加了@TableField的时间字段进行时间填充

java 复制代码
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_job")
public class Job {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String jobName;

    private String jobGroup;

    private String invokeTarget;

    private String cronExpression;

    private Integer misfirePolicy;

    private Integer concurrent;

    private Integer status;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.UPDATE)
    private LocalDateTime updateTime;

    private String remark;

    @TableField(exist = false)
    private Date nextValidTime;

}
相关推荐
圆山猫1 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管2 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨2 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡3 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖3 小时前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One9853 小时前
高进度算法模板速记(待完善)
java·前端·算法
极光代码工作室5 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen6 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
名字还没想好☜7 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
圆山猫7 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v