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;

}
相关推荐
心态与习惯35 分钟前
Julia 初探,及与 C++,Java,Python 的比较
java·c++·python·julia·比较
一叶飘零_sweeeet1 小时前
优秀文章合集
java
zopple1 小时前
ThinkPHP5.x与3.x核心差异解析
java·python·php
南境十里·墨染春水2 小时前
C++ 笔记 thread
java·开发语言·c++·笔记·学习
南境十里·墨染春水2 小时前
C++ 笔记 高级线程同步原语与线程池实现
java·开发语言·c++·笔记·学习
阿巴斯甜2 小时前
Predicate的使用:
java
阿巴斯甜2 小时前
Supplier的使用:
java
阿巴斯甜2 小时前
Function 用法:
java
做个文艺程序员3 小时前
流式输出(SSE)在 Spring Boot 中的实现【OpenClAW + Spring Boot 系列 第3篇】
java·spring boot·后端
逻辑驱动的ken3 小时前
Java高频面试考点场景题09
java·开发语言·数据库·算法·oracle·哈希算法·散列表