Best practice summary of Mybatis plus general field automatic filling

When performing persistence layer data maintenance (addition or modification), we usually need to record some non-business fields, such as: create_time, update_time, update_by, create_by, etc. to maintain the creation time, modification time, modification person, and creation of the data record People and other information. Under normal circumstances, we need to manually assign values ​​to these fields. The assignment process is also relatively redundant, all of which are repeated operations.

  • Usually, create_time is assigned the current time of the system, and update_time is assigned the current time when the system modification operation is executed.
  • create_by (creator), update_by (modifier) ​​are assigned to the username of the current logged in user
xxxYyyZzz.setUpdateBy("zimug");    //数据记录更新操作人
xxxYyyZzz.setUpdateTime(new Date());   //数据记录更新操作的时间

Mybatis plus provides us with a once-and-for-all automatic assignment method.

One, adjust the database table structure

Take the xxx_yyy_zzz table in the mysql database environment as an example. On the basis of the original table fields, add the following four general data maintenance fields.

ALTER TABLE `xxx_yyy_zzz` ADD COLUMN `create_by` VARCHAR(64) NOT NULL COMMENT '本条记录创建人';
ALTER TABLE `xxx_yyy_zzz` ADD COLUMN `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '本条记录创建时间';
ALTER TABLE `xxx_yyy_zzz` ADD COLUMN `update_by` VARCHAR(64) NOT NULL COMMENT '本条记录修改人';
ALTER TABLE `xxx_yyy_zzz` ADD COLUMN `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '本条记录的修改时间';

Second, the general maintenance information parent class-automatically assigned fields

Now that we are maintaining the new creation and modification information of a certain table of data, our entity classes also need to be adjusted as necessary. In order to avoid adding these four member variables to each entity class, we define a parent class BaseColumns.

@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;


}
  • fill = FieldFill.INSERT means that the field is automatically assigned a value during the insert operation
  • fill = FieldFill.INSERT_UPDATE means that the field is automatically assigned a value during nsert or update operation
  • select = false means that the database field corresponding to this attribute will not be queried when using the Mybatis Wrapper condition builder to query. The data modification time operator is usually more meaningful for operation and maintenance, so it usually does not need to be displayed on the web page, so it is usually not included in the select query. (This content is not directly related to the field auto-fill of our machine, but it is meaningful in practical applications)

Three, the realization of the entity class

The entity class XxxYyyZzz below corresponds to the xxx_yyy_zzz table in the database. In addition to the above four general fields, the xxx_yyy_zzz table also contains other business fields.

@Data
@EqualsAndHashCode(callSuper = true)
public class XxxYyyZzz extends BaseColumns {

    //其他的属性字段
}

Fourth, the rules of automatic assignment

@Component
public class MybastisColumnsHandler 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());
    }
}
  • When data is added, createTime, updateTime, createBy, and updateBy are automatically assigned, that is, data is initialized.
  • When data is modified, updateTime and updateBy are automatically assigned.
  • JwtTokenUtil is a tool class I wrote to get the user name of the currently logged-in user from the currently logged-in user JWT Token. (The method of obtaining the current login user name in your system is different from mine, but it can be obtained anyway)

Five, achieve the effect

For example, when the data is updated, the following two lines of code do not need to be written, and are updateFill(MetaObject metaObject)automatically completed

//xxxYyyZzz.setUpdateBy("zimug");    //数据记录更新操作人
//xxxYyyZzz.setUpdateTime(new Date());   //数据记录更新操作的时间

xxxYyyZzzMapper.updateById(xxxYyyZzz);

Similarly, when the data insert operation, it insertFill(MetaObject metaObject)will be automatically executed.

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/113247807