需要注意的是,MetaObjectHandler 对Mybatis-plus 自动生成的 CRUD 方法起作用,对于手写 XML 文件的 insert、update 语句,不会直接起作用。
package com.ruoyi.common.mybatisplus;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.util.Date;@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.strictInsertFill(metaObject, "createTime", Date.class, new Date());this.strictInsertFill(metaObject, "createUser", String.class, SecurityUtils.getUsername());this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());this.strictInsertFill(metaObject, "updateUser", String.class, SecurityUtils.getUsername());}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject);this.setFieldValByName("updateUser", SecurityUtils.getUsername(), metaObject);//strictUpdateFill 对字段有值不起作用// this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());// this.strictUpdateFill(metaObject, "updateUser", String.class, SecurityUtils.getUsername());}}