MyMetaObjectHandler.java 1.88 KB
package com.tianting.infoloop.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tianting.infoloop.context.ContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.tianting.infoloop.constants.ConfigConstants.NOT_DELETED_FLAG;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, NOT_DELETED_FLAG);
        final var userId = ContextHolder.getUserId();
        final var source = ContextHolder.getSource();
        if (userId != null) {
            this.strictInsertFill(metaObject, "createdBy", Integer.class, userId);
            this.strictInsertFill(metaObject, "updatedBy", Integer.class, userId);
        }
        if (source != null) {
            this.strictInsertFill(metaObject, "creationSource", Integer.class, source);
            this.strictInsertFill(metaObject, "updateSource", Integer.class, source);
        }
    }

    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        final var userId = ContextHolder.getUserId();
        final var source = ContextHolder.getSource();
        if (userId != null) {
            this.strictInsertFill(metaObject, "updatedBy", Integer.class, userId);
        }
        if (source != null) {
            this.strictInsertFill(metaObject, "updateSource", Integer.class, source);
        }
    }
}