|
@@ -0,0 +1,81 @@
|
|
|
|
+package com.xynet.marketing.config;
|
|
|
|
+
|
|
|
|
+import cn.hutool.core.util.StrUtil;
|
|
|
|
+import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
|
+import org.apache.ibatis.reflection.MetaObject;
|
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
|
+import org.springframework.util.ClassUtils;
|
|
|
|
+
|
|
|
|
+import java.nio.charset.Charset;
|
|
|
|
+import java.time.LocalDateTime;
|
|
|
|
+
|
|
|
|
+/***
|
|
|
|
+ * Mybatis-plus自动填充
|
|
|
|
+ * @author 谭斌
|
|
|
|
+ * @date 2023/2/16 18:57
|
|
|
|
+ */
|
|
|
|
+@Slf4j
|
|
|
|
+@Component
|
|
|
|
+public class MyBatisMetaObjectHandler implements MetaObjectHandler {
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 创建时间
|
|
|
|
+ */
|
|
|
|
+ public static final String CREATE_TIME_FIELD = "createTime";
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 更新时间
|
|
|
|
+ */
|
|
|
|
+ public static final String REVISE_TIME_FIELD = "updateTime";
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 创建用户ID
|
|
|
|
+ */
|
|
|
|
+ public static final String CREATE_USER_ID_FIELD = "createUser";
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 更新用户ID
|
|
|
|
+ */
|
|
|
|
+ public static final String REVISE_USER_ID_FIELD = "updateUser";
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void insertFill(MetaObject metaObject) {
|
|
|
|
+ log.debug("insert fill -> {}表", metaObject.getOriginalObject().getClass().getSimpleName());
|
|
|
|
+ fillValIfNullByName(CREATE_TIME_FIELD, LocalDateTime.now(), metaObject, false);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void updateFill(MetaObject metaObject) {
|
|
|
|
+ log.debug("update fill -> {}表", metaObject.getOriginalObject().getClass().getSimpleName());
|
|
|
|
+ fillValIfNullByName(REVISE_TIME_FIELD, LocalDateTime.now(), metaObject, true);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 填充值,先判断是否有手动设置,优先手动设置的值
|
|
|
|
+ *
|
|
|
|
+ * @param fieldName 属性名
|
|
|
|
+ * @param fieldVal 属性值
|
|
|
|
+ * @param metaObject MetaObject
|
|
|
|
+ * @param isCover 是否覆盖原有值,避免更新操作手动入参
|
|
|
|
+ */
|
|
|
|
+ private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
|
|
|
|
+ // 1. 没有 set 方法
|
|
|
|
+ if (!metaObject.hasSetter(fieldName)) {
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+ // 2. 如果用户有手动设置的值
|
|
|
|
+ Object userSetValue = metaObject.getValue(fieldName);
|
|
|
|
+ String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
|
|
|
|
+ if (StrUtil.isNotBlank(setValueStr) && !isCover) {
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+ // 3. field 类型相同时设置
|
|
|
|
+ Class<?> getterType = metaObject.getGetterType(fieldName);
|
|
|
|
+ if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
|
|
|
|
+ metaObject.setValue(fieldName, fieldVal);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|