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;

}
相关推荐
鸽鸽程序猿几秒前
【项目】【抽奖系统】活动创建
java·spring
不平衡的叉叉树8 分钟前
Mybatis常用动态SQL标签
java·mybatis
电子_咸鱼1 小时前
动态规划经典题解:单词拆分(LeetCode 139)
java·数据结构·python·算法·leetcode·线性回归·动态规划
李慕婉学姐1 小时前
【开题答辩过程】以《割草机器人工作管理系统的设计与开发》为例,不会开题答辩的可以进来看看
java·spring·机器人
青衫码上行1 小时前
【Java Web学习 | 第七篇】JavaScript(1) 基础知识1
java·开发语言·前端·javascript·学习
堕落年代1 小时前
Spring三级缓存通俗易懂讲解
java·spring·缓存
披着羊皮不是狼2 小时前
多用户博客系统搭建(1):表设计+登录注册接口
java·开发语言·springboot
WX-bisheyuange5 小时前
基于Spring Boot的教师个人成果管理系统的设计与实现
java·spring boot·后端
chxii5 小时前
spring boot 获取HTTP 请求参数
spring boot·后端·http
xunyan62346 小时前
面向对象(上)-封装性的引入
java·开发语言