遵守诺言就象保卫你的荣誉一样。——巴尔扎克
官方文档里说首先需要加@TableField
注解并指定fill
的值
对应的值在com.baomidou.mybatisplus.annotation.FieldFill
这个枚举里
例如我这里gmtCreate
字段需要在新增的时候自动填充,就使用FieldFill.INSERT
然而我需要让gmtModified
字段在新增和修改的时候都自动填充,就使用FieldFill.INSERT_UPDATE
不过,加了注解后咱们还得去注入一个com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
完整代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package com.ruben.simpleideaboot.config;
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.handlers.StrictFill; import com.baomidou.mybatisplus.core.toolkit.LambdaUtils; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import com.ruben.simpleideaboot.pojo.User; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.property.PropertyNamer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime; import java.util.Arrays;
@Configuration public class MybatisPlusConfig {
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); PaginationInnerInterceptor innerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); innerInterceptor.setOverflow(true); innerInterceptor.setMaxLimit(200L); interceptor.addInnerInterceptor(innerInterceptor); return interceptor; }
@Bean public MetaObjectHandler metaObjectHandler() { return new MetaObjectHandler() {
@Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(findTableInfo(metaObject), metaObject, Arrays.asList( StrictFill.of(PropertyNamer.methodToProperty(LambdaUtils.resolve(User::getGmtCreate) .getImplMethodName()), LocalDateTime::now, LocalDateTime.class), StrictFill.of("gmtModified", LocalDateTime.class, LocalDateTime.now()) )); }
@Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "gmtModified", () -> LocalDateTime.now(), LocalDateTime.class); } }; }
}
|
然后调用insert
方法或者update
方法就会自动更新上去啦