一、引入依赖
<!-- mybatis-plus-boot-starter-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
二、配置类
这里我主要对字段createTime和updateTime进行自动填充,你们可以修改为自己对应的字段即可。文章来源:https://www.toymoban.com/news/detail-823313.html
@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的时间字段进行时间填充文章来源地址https://www.toymoban.com/news/detail-823313.html
@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;
}
到了这里,关于Mybtisplus对时间字段进行自动填充的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!