Mybatis Plus公共字段自动填充-动力节点

如果你使用了Mybatis Plus,可以借助于其自动填充功能来实现。

基于 Mybatis Plus 3.3.0

只需要实现MetaObjectHandler接口:br/>@Component
public class MybatisAuditHandler implements MetaObjectHandler {
br/>@Override
public void insertFill(MetaObject metaObject) {
// 声明自动填充字段的逻辑。
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());
}

}
然后我们扩展一下Mybatis Plus的Model把公共审计字段放进去并声明对应的填充策略:
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;
}

最后我们的实体类不再直接继承Model改为上面的BaseEntity: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;
}
}

这样我们就不用再关心这几个公共字段了,当然你可以根据需要添加更多你需要填充的字段。

猜你喜欢

转载自blog.51cto.com/14881077/2540821