metaObjecthandler 的基本理解与使用(自动插入更新人和创建人)
metaObjecthandler 的基本理解与使用(自动插入更新人和创建人)
mysql 自动插入更新和修改时间
更新字段信息
ALTER TABLE test MODIFY create_date timestamp not null default CURRENT_TIMESTAMP;
ALTER TABLE test MODIFY update_date timestamp not null default CURRENT_TIMESTAMP on update
CURRENT_TIMESTAMP;
metaObjecthandler:元数据对象处理器
MetaObjectHandler接口是mybatisPlus为我们提供的的一个扩展接口,我们可以利用这个接口在我们插入或者更新数据的时候,为一些字段指定默认值。
使用场景:公共字段填充等,如updateTime、createTime、createUser、updateUser等公共字段多的填充。
基本使用:
1.实体的公共字段使用@TableField注解;
@TebleField(fill = FieldFill.INSERT):表示此字段只在插入/新增操作时更新数据@TebleField(fill = FieldFill.INSERT_UPDATE):表示此字段在修改和新增操作时都更新数据;@TebleField(fill = FieldFill.UPDATE):表示此字段只在修改操作时都更新数据;
代码如下
@Data
public class Employee implements Serializable {private static final long serialVersionUID = 1L;private Long id;private String username;@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;@TableField(fill = FieldFill.INSERT)
private Long createUser;@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;}
2.自定义元对象处理器类,实现metaObjecthandler接口,重写insertFill、updateFill方法;
1)在每次执行插入和修改操作时,会执行insertFill,updateFill方法;
2)setValue(String name,Object value) : 设置公共字段填充值,第一个参数值name与实体字段要相同;
@Slf4j
@Component
public class MyMetaObjecthandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("公共字段自动填充【insert】");log.info(metaObject.toString());metaObject.setValue("createTime", LocalDateTime.now());metaObject.setValue("updateTime", LocalDateTime.now());metaObject.setValue("createUser", new Long(1));metaObject.setValue("updateUser", new Long(1));}@Overridepublic void updateFill(MetaObject metaObject) {log.info("公共字段自动填充【update】");log.info(metaObject.toString());metaObject.setValue("updateTime", LocalDateTime.now());metaObject.setValue("updateUser", new Long(1));}
}