文章目录
- 1、自定义实现类 MyMetaObjectHandler
- 2、在entity中标记需要自动填充的属性
- 3、FieldFill中有哪些字段
1、自定义实现类 MyMetaObjectHandler
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @BelongsProject: pushService
* @Author: Yuan Haozhe
* @CreateTime: 2023-07-10 11:24
* @Description: 自动填充处理器
* @Version: 1.0
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "createBy", String.class, "admin");
this.strictInsertFill(metaObject, "updateBy", String.class, "admin");
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
this.strictUpdateFill(metaObject, "updateBy", String.class, "admin");
}
}
2、在entity中标记需要自动填充的属性
@Data
@TableName("sys_post")
public class PostPO {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String postCode;
private String postName;
private Integer status;
private String remark;
// 注意!这里需要标记为填充字段
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private String createBy;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
@TableLogic
private Integer deleteFlag;
private Integer revision;
3、FieldFill中有哪些字段
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入时填充字段
*/
INSERT,
/**
* 更新时填充字段
*/
UPDATE,
/**
* 插入和更新时填充字段
*/
INSERT_UPDATE
}
根据数据表的设计,status默认值是1,remark默认值是“”,所以执行添加的时候,status和remark可以不用传,
在controller中调用service的save(T t)后,查看效果: