一、引入依赖
<!-- mybatis-plus-boot-starter--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency>
二、配置类
这里我主要对字段createTime和updateTime进行自动填充,你们可以修改为自己对应的字段即可。
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);}
}
三、使用填充功能
在需要填充的字段上加入 @TableField(fill = FieldFill.INSERT)或者 @TableField(fill = FieldFill.UPDATE),当执行SQL语句时就会拦截语句随后对SQL语句添加了@TableField的时间字段进行时间填充
@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;}