阿超
>
MybatisPlus自动填充忽略存在值直接填充
再也无需前思后想,一切岂非已然过往。——《且听风吟》
代码如下,主要是重写strictFillStrategy
方法
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
| import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.lang.Opt; import com.baomidou.mybatisplus.core.MybatisConfiguration; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.handlers.StrictFill; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.apache.ibatis.reflection.MetaObject; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime; import java.util.List; import java.util.Objects; import java.util.function.Supplier;
@Configuration @ConditionalOnClass(MybatisConfiguration.class) public class MyBatisPlusConfiguration {
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; }
@Bean public MetaObjectHandler metaObjectHandler() { return new MetaObjectHandler() {
@Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(findTableInfo(metaObject), metaObject, List.of( StrictFill.of("createAt", LocalDateTime.class, LocalDateTime.now()), StrictFill.of("updateAt", LocalDateTime.class, LocalDateTime.now()), StrictFill.of("createBy", () -> Opt.ofTry(StpUtil::getLoginIdAsLong).get(), Long.class), StrictFill.of("updateBy", () -> Opt.ofTry(StpUtil::getLoginIdAsLong).get(), Long.class) )); }
@Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(findTableInfo(metaObject), metaObject, List.of( StrictFill.of("updateAt", LocalDateTime.class, LocalDateTime.now()), StrictFill.of("updateBy", () -> Opt.ofTry(StpUtil::getLoginIdAsLong).get(), Long.class) )); }
@Override public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) { Object obj = fieldVal.get(); if (Objects.nonNull(obj)) { metaObject.setValue(fieldName, obj); } return this; } }; }
}
|