通用字段填充

12/13/2023

# 定义父类信息

@Data
public class BaseColumns {

  /**
   * 本条记录创建人,insert操作的时候自动为该字段赋值
   */
  @TableField(fill = FieldFill.INSERT)
  private String createBy;

  /**
   * 本条记录创建时间,insert操作的时候自动为该字段赋值
   */
  @TableField(fill = FieldFill.INSERT)
  private LocalDateTime  createTime;

  /**
   * 本条记录更新人,insert或update操作的时候自动为该字段赋值,select = false
   */
  @TableField(fill = FieldFill.INSERT_UPDATE,select = false)  
  private String updateBy;

  /**
   * 本条记录更新时间,insert或update操作的时候自动为该字段赋值,select = false
   */
  @TableField(fill = FieldFill.INSERT_UPDATE,select = false)
  private LocalDateTime updateTime;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 定义赋值规则

@Component
public class MybatisColumnsHandler implements MetaObjectHandler {

    @Resource
    private JwtTokenUtil jwtTokenUtil;  //我的工具类,用于从Token令牌中获取登陆人信息

    //设置数据新增时候的,字段自动赋值规则
    @Override
    public void insertFill(MetaObject metaObject) {
      this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
      this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

      this.strictInsertFill(metaObject, "createBy", String.class, jwtTokenUtil.getUsernameFromToken());
      this.strictUpdateFill(metaObject, "updateBy", String.class, jwtTokenUtil.getUsernameFromToken());
    }

    //设置数据修改update时候的,字段自动赋值规则
    @Override
    public void updateFill(MetaObject metaObject) {
      this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
      this.strictUpdateFill(metaObject, "updateBy", String.class, jwtTokenUtil.getUsernameFromToken());
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24