MP之时间创建人修改人自动填充

依赖 3.5.2


    com.baomidou
    mybatis-plus-boot-starter
    ${mybatis-plus.version}

=====================================

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.time.LocalDateTime;

@Component
public class MyMeatObjecthandler implements MetaObjectHandler {

    /*数据库添加操作自动填充*/
    @Override
    public void insertFill(MetaObject metaObject) {
        /*log.info("公共字段自动填充insert");*/
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentID());
        metaObject.setValue("updateUser", BaseContext.getCurrentID());

    }

    /*数据库修改操作自动填充*/
    @Override
    public void updateFill(MetaObject metaObject) {
       /* log.info("公共字段自动填充update");*/
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentID());
    }

}

==========================================

import org.springframework.stereotype.Component;

/*一次会话线程中id获取于注入*/
@Component
public class BaseContext {
    private static ThreadLocal threadLocal = new ThreadLocal();

    public static void setCurrentID(Long id) {
        threadLocal.set(id);
    }
    public static Long getCurrentID() {
        return threadLocal.get();
    }
}

=====================

使用

 @TableField(fill = FieldFill.INSERT) //插入时填充字段
   @TableField(fill = FieldFill.INSERT_UPDATE) //插入和更新时填充字段
@Data
public class AddressBook implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;


    //用户id
    private Long userId;


    //收货人
    private String consignee;


    //手机号
    private String phone;


    //性别 0 女 1 男
    private String sex;


    //省级区划编号
    private String provinceCode;


    //省级名称
    private String provinceName;


    //市级区划编号
    private String cityCode;


    //市级名称
    private String cityName;


    //区级区划编号
    private String districtCode;


    //区级名称
    private String districtName;


    //详细地址
    private String detail;


    //标签
    private String label;

    //是否默认 0 否 1是
    private Integer isDefault;

    //创建时间
    @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;


    //是否删除
    private Integer isDeleted;

你可能感兴趣的:(java,服务器,前端)