在使用BaseMapper里面的insert和update时,可以自动填充实体中的create_time,create_user,update_time,update_user
实现MetaObjectHandler:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component(value = "customMetaObjectHandler")
@Primary
public class CustomMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
metaObject.setValue("createTime", null);
metaObject.setValue("updateTime", null);
metaObject.setValue("createUser", null);
metaObject.setValue("updateUser", null);
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
this.strictInsertFill(metaObject, "createUser", String.class, UserUtils.getCurrentUserUidOrSystemId());
this.strictInsertFill(metaObject, "updateUser", String.class, UserUtils.getCurrentUserUidOrSystemId());
}
@Override
public void updateFill(MetaObject metaObject) {
metaObject.setValue("updateTime", null);
metaObject.setValue("updateUser", null);
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
this.strictInsertFill(metaObject, "updateUser", String.class, UserUtils.getCurrentUserUidOrSystemId());
}
}
实体类代码:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(fill = FieldFill.INSERT, value = "CREATE_TIME")
private Date createTime;
@TableField(fill = FieldFill.INSERT, value = "CREATE_USER")
private String createUser;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(fill = FieldFill.INSERT_UPDATE, value = "UPDATE_TIME")
private Date updateTime;
@TableField(fill = FieldFill.INSERT_UPDATE, value = "UPDATE_USER")
private String updateUser;