package com.ruoyi.article.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.ruoyi.common.security.utils.SecurityUtils; import java.time.LocalDateTime; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; /** * 自动填充处理类 * * @author mitao * @date 2024-05-16 */ @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { // 获取当前登录用户 Long userId = SecurityUtils.getUserId(); fillValue("createBy", userId.toString(), metaObject); fillValue("createTime", LocalDateTime.now(), metaObject); } @Override public void updateFill(MetaObject metaObject) { // 获取当前登录用户 Long userId = SecurityUtils.getUserId(); fillValue("updateBy", userId.toString(), metaObject); fillValue("updateTime", LocalDateTime.now(), metaObject); } private void fillValue(String fieldName, Object data, MetaObject metaObject) { if (metaObject.hasSetter(fieldName)) { // 值为空时设置默认值 Object sidObj = getFieldValByName(fieldName, metaObject); if (sidObj == null || "updateBy".equals(fieldName) || "updateTime".equals(fieldName)) { setFieldValByName(fieldName, data, metaObject); } } } }