Mybatis-plus 使用MetaObjectHandler進(jìn)行公共字段全局填充

前言

在項(xiàng)目中,經(jīng)常會(huì)有一些公共字段,例如createUser,createTime,isDeleted等,需要全局賦值,來(lái)看看在Springboot中怎么做吧。

使用

填充類型

public enum FieldFill {
    DEFAULT,  //默認(rèn)
    INSERT,    //插入時(shí)填充
    UPDATE,  //更新時(shí)填充
    INSERT_UPDATE;  //插入和更新時(shí)填充

    private FieldFill() {
    }
}

使用方法

只需要在字段上添加@TableField注解,并設(shè)置注解屬性 fill = FieldFill.INSERT即可。

//實(shí)體類
@Data
public class Demo {
 @TableField(value = "create_time", fill = FieldFill.INSERT)
 private Date createTime;
 @TableField(value = "create_user", fill = FieldFill.INSERT)
 private String createUser;
 @TableField(value = "update_time", fill = FieldFill.UPDATE)
 private Date updateTime;
}
@Configuration
public class MyBatisPlusConfig {

    /**
     * 解決了insert/update數(shù)據(jù)時(shí)默認(rèn)值問(wèn)題
     * @return
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
                Object createTime = this.getFieldValByName("createTime", metaObject);
                if(Objects.isNull(createTime)) {
                    this.setFieldValByName("createTime", new Date(System.currentTimeMillis()), metaObject);
                }
                this.setFieldValByName("createUser", "admin", metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
                this.setFieldValByName("updateTime", new Date(System.currentTimeMillis()), metaObject);
            }
        };
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容