Mybatis Plus public fields are automatically filled-power node

If you use Mybatis Plus, you can do it with the help of its auto-fill function.

Based on Mybatis Plus 3.3.0

You only need to implement the MetaObjectHandler interface: br/>@Component
public class MybatisAuditHandler implements MetaObjectHandler {
br/>@Override
public void insertFill(MetaObject metaObject) {
// Declare the logic of auto-filling fields.
String userId = AuthHolder.getCurrentUserId();
this.strictInsertFill(metaObject,"creator",String.class, userId);
this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
}

@Override
public void updateFill(MetaObject metaObject) {
// 声明自动填充字段的逻辑。
String userId = AuthHolder.getCurrentUserId();
this.strictUpdateFill(metaObject,"updater",String.class,userId);
this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
}

}
Then we extend the Mybatis Plus Model to put the public audit field in and declare the corresponding filling strategy:
public abstract class BaseEntity<T extends Model<?>> extends Model {
@TableField(fill = FieldFill.INSERT)
private String creator;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime addTime;
@TableField(fill = FieldFill.UPDATE)
private String updater;
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
}

Finally, our entity class no longer directly inherits from Model to BaseEntity above: br/>@Data
@EqualsAndHashCode(callSuper = false)
public class UserInfo extends BaseEntity {
@TableId(value = “user_id”, type = IdType.ASSIGN_ID)
private String userId;
private String username;

@Override
protected Serializable pkVal() {
return this.userId;
}
}

So we don't need to care about these public fields anymore, of course you can add more fields you need to fill in as needed.

Guess you like

Origin blog.51cto.com/14881077/2540821