Browse Source

取消原来的AnnoEnum注解,使用MetaObjectHandler来进行自动注入

陈长荣 2 weeks ago
parent
commit
86ded3a27f

+ 2 - 2
jfcloud-gene-biz/src/main/java/com/github/jfcloud/gene/cache/UserIdNameCache.java

@@ -48,9 +48,9 @@ public class UserIdNameCache {
     private RemoteUserService remoteUserService;
     private RemoteUserService remoteUserService;
 
 
     /**
     /**
-     * 每日5点整清空缓存
+     * 清空缓存
      */
      */
-    @Scheduled(cron = "0 0 5 * * ?")
+    @Scheduled(cron = "0 0 */4 * * ?")
     public void clearCache() {
     public void clearCache() {
         log.info("清空用户缓存");
         log.info("清空用户缓存");
         idMap.clear();
         idMap.clear();

+ 16 - 0
jfcloud-gene-biz/src/main/java/com/github/jfcloud/gene/config/CoreConfig.java

@@ -0,0 +1,16 @@
+package com.github.jfcloud.gene.config;
+
+import com.github.jfcloud.gene.handler.BaseEntityMetaObjectHandler;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+@Configuration
+public class CoreConfig {
+
+    @Bean
+    @Primary
+    public BaseEntityMetaObjectHandler metaObjectHandler() {
+        return new BaseEntityMetaObjectHandler();
+    }
+}

+ 2 - 2
jfcloud-gene-biz/src/main/java/com/github/jfcloud/gene/config/OpenApiConfig.java

@@ -17,8 +17,8 @@ public class OpenApiConfig {
         return new OpenAPI()
         return new OpenAPI()
                 .info(new Info()
                 .info(new Info()
                         .title("基因定制 & 样本送检  API")
                         .title("基因定制 & 样本送检  API")
-                        .version("2.0.0")
-                        .version("2.0.0")
+                        .version("3.0.0")
+                        .version("3.0.0")
                         .description("基因定制:动物品系定制、动物品系净化扩繁<br>样本送检:病理样本检测、动物样本检测、动物影像检测、宠物食品检测"));
                         .description("基因定制:动物品系定制、动物品系净化扩繁<br>样本送检:病理样本检测、动物样本检测、动物影像检测、宠物食品检测"));
     }
     }
 }
 }

+ 1 - 5
jfcloud-gene-biz/src/main/java/com/github/jfcloud/gene/flow/entity/FlowFileVersion.java

@@ -4,8 +4,6 @@ import com.baomidou.mybatisplus.annotation.FieldFill;
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.extension.activerecord.Model;
 import com.baomidou.mybatisplus.extension.activerecord.Model;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonFormat;
-import com.github.jfcloud.gene.common.interceptor.anno.AutoStuff;
-import com.github.jfcloud.gene.common.interceptor.enums.AnnoEnum;
 import lombok.Data;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.EqualsAndHashCode;
 import lombok.experimental.Accessors;
 import lombok.experimental.Accessors;
@@ -66,14 +64,12 @@ public class FlowFileVersion extends Model implements Serializable {
      * 创建人
      * 创建人
      */
      */
     @TableField(fill = FieldFill.INSERT)
     @TableField(fill = FieldFill.INSERT)
-    @AutoStuff(annoType = AnnoEnum.CREATE_BY)
     private String createBy;
     private String createBy;
 
 
     /**
     /**
      * 创建时间
      * 创建时间
      */
      */
-    @TableField(fill = FieldFill.INSERT, value = "create_time")
-    @AutoStuff(annoType = AnnoEnum.CREATE_TIME)
+    @TableField(fill = FieldFill.INSERT)
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private Date createTime;
     private Date createTime;
 
 

+ 79 - 0
jfcloud-gene-biz/src/main/java/com/github/jfcloud/gene/handler/BaseEntityMetaObjectHandler.java

@@ -0,0 +1,79 @@
+package com.github.jfcloud.gene.handler;
+
+import cn.hutool.core.util.StrUtil;
+import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
+import com.github.jfcloud.common.security.util.SecurityUtils;
+import com.github.jfcloud.gene.common.util.UserUtil;
+import org.apache.ibatis.reflection.MetaObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.ClassUtils;
+
+import java.nio.charset.Charset;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class BaseEntityMetaObjectHandler implements MetaObjectHandler {
+
+    private static final Logger log = LoggerFactory.getLogger(BaseEntityMetaObjectHandler.class);
+
+    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
+        if (fieldVal != null) {
+            if (metaObject.hasSetter(fieldName)) {
+                Object userSetValue = metaObject.getValue(fieldName);
+                String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
+                if (!StrUtil.isNotBlank(setValueStr) || isCover) {
+                    Class<?> getterType = metaObject.getGetterType(fieldName);
+                    if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
+                        metaObject.setValue(fieldName, fieldVal);
+                    }
+
+                }
+            }
+        }
+    }
+
+    public void insertFill(MetaObject metaObject) {
+        log.debug("mybatis plus start insert fill ....");
+        Map<String, Object> fieldsToFill = new HashMap<>();
+        fieldsToFill.put("createTime", new Date());
+        fieldsToFill.put("create_time", new Date());
+        fieldsToFill.put("createBy", UserUtil.getUserName());
+        fieldsToFill.put("delFlag", "0");
+        fieldsToFill.put("deleted", "0");
+        fieldsToFill.put("deptId", UserUtil.getDeptId());
+        fieldsToFill.put("groupIndex", this.getGroupIndex());
+        fieldsToFill.put("groupPi", this.getGroupPi());
+        fieldsToFill.put("tenantId", UserUtil.getTenantId());
+        this.fillFieldsIfExist(metaObject, fieldsToFill, false);
+    }
+
+    private void fillFieldsIfExist(MetaObject metaObject, Map<String, Object> fieldsToFill, boolean isCover) {
+        for(Map.Entry<String, Object> entry : fieldsToFill.entrySet()) {
+            String fieldName = entry.getKey();
+            Object defaultValue = entry.getValue();
+            if (metaObject.hasGetter(fieldName)) {
+                fillValIfNullByName(fieldName, defaultValue, metaObject, isCover);
+            }
+        }
+
+    }
+
+    public void updateFill(MetaObject metaObject) {
+        Map<String, Object> fieldsToFill = new HashMap<>();
+        fieldsToFill.put("updateTime", new Date());
+        fieldsToFill.put("update_time", new Date());
+        fieldsToFill.put("updateBy", UserUtil.getUserName());
+        this.fillFieldsIfExist(metaObject, fieldsToFill, false);
+    }
+
+
+    private Integer getGroupIndex() {
+        return SecurityUtils.getGroupIndex();
+    }
+
+    private Long getGroupPi() {
+        return SecurityUtils.getGroupPi();
+    }
+}

+ 3 - 11
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/entity/BaseEntity.java

@@ -6,8 +6,6 @@ import com.baomidou.mybatisplus.annotation.TableLogic;
 import com.baomidou.mybatisplus.extension.activerecord.Model;
 import com.baomidou.mybatisplus.extension.activerecord.Model;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.github.jfcloud.gene.common.interceptor.anno.AutoStuff;
-import com.github.jfcloud.gene.common.interceptor.enums.AnnoEnum;
 import lombok.Data;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.EqualsAndHashCode;
 import lombok.experimental.Accessors;
 import lombok.experimental.Accessors;
@@ -21,29 +19,23 @@ import java.util.Date;
 public abstract class BaseEntity extends Model implements Serializable {
 public abstract class BaseEntity extends Model implements Serializable {
 
 
     @TableField(fill = FieldFill.INSERT)
     @TableField(fill = FieldFill.INSERT)
-    @AutoStuff(annoType = AnnoEnum.TENANT_ID)
     private Long tenantId;
     private Long tenantId;
 
 
     @TableField(fill = FieldFill.INSERT)
     @TableField(fill = FieldFill.INSERT)
-    @AutoStuff(annoType = AnnoEnum.DEPT_ID)
     private Long deptId;
     private Long deptId;
 
 
-    @TableField(fill = FieldFill.INSERT, value = "create_time")
-    @AutoStuff(annoType = AnnoEnum.CREATE_TIME)
+    @TableField(fill = FieldFill.INSERT)
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private Date createTime;
     private Date createTime;
 
 
-    @TableField(fill = FieldFill.INSERT_UPDATE, value = "update_time")
-    @AutoStuff(annoType = AnnoEnum.UPDATE_TIME)
+    @TableField(fill = FieldFill.INSERT_UPDATE)
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private Date updateTime;
     private Date updateTime;
 
 
     @TableField(fill = FieldFill.INSERT)
     @TableField(fill = FieldFill.INSERT)
-    @AutoStuff(annoType = AnnoEnum.CREATE_BY)
     private String createBy;
     private String createBy;
 
 
     @TableField(fill = FieldFill.INSERT_UPDATE)
     @TableField(fill = FieldFill.INSERT_UPDATE)
-    @AutoStuff(annoType = AnnoEnum.UPDATE_BY)
     private String updateBy;
     private String updateBy;
 
 
     /**
     /**
@@ -51,7 +43,7 @@ public abstract class BaseEntity extends Model implements Serializable {
      */
      */
     @JsonIgnore
     @JsonIgnore
     @TableLogic(value = "0", delval = "1")
     @TableLogic(value = "0", delval = "1")
-    @TableField(value = "deleted")
+    @TableField(fill = FieldFill.INSERT)
     private String deleted = "0";
     private String deleted = "0";
 
 
 }
 }

+ 0 - 14
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/anno/AutoStuff.java

@@ -1,14 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.anno;
-
-import com.github.jfcloud.gene.common.interceptor.enums.AnnoEnum;
-
-import java.lang.annotation.*;
-
-@Target({ElementType.FIELD})
-@Retention(RetentionPolicy.RUNTIME)
-@Inherited
-@Documented
-public @interface AutoStuff {
-
-    AnnoEnum annoType();
-}

+ 0 - 32
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/config/InterceptorConfig.java

@@ -1,32 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.config;
-
-
-import com.github.jfcloud.gene.common.interceptor.interceptor.StuffInterceptor;
-import org.apache.ibatis.plugin.Interceptor;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-
-@Configuration
-@EnableConfigurationProperties({MybatisInterceptorProperties.class})// 激活配置模块
-/**
- * 控制Configuration是否生效
- * name: 数组,property完整名称或部分名称
- * matchIfMissing:缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
- * havingValue: 比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
- */
-@ConditionalOnProperty(
-        name = {"my.interceptor.enabled"},
-        matchIfMissing = true,
-        havingValue = "true"
-)
-public class InterceptorConfig {
-
-    @Bean
-    public Interceptor getStuffInterceptor() {
-        return new StuffInterceptor();
-    }
-
-}

+ 0 - 19
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/config/MybatisInterceptorProperties.java

@@ -1,19 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.config;
-
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
-@ConfigurationProperties(
-        prefix = "my.interceptor", ignoreInvalidFields = true
-)
-public class MybatisInterceptorProperties {
-    // 默认为true
-    private Boolean enabled = Boolean.TRUE;
-
-    public Boolean getEnabled() {
-        return enabled;
-    }
-
-    public void setEnabled(Boolean enabled) {
-        this.enabled = enabled;
-    }
-}

+ 0 - 23
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/enums/AnnoEnum.java

@@ -1,23 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.enums;
-
-public enum AnnoEnum {
-
-    TENANT_ID("tenantId"),
-    ORG_ID("orgId"),
-    DEPT_ID("deptId"),
-    CREATE_BY("createBy"),
-    CREATE_TIME("createTime"),
-    UPDATE_BY("updateBy"),
-    UPDATE_TIME("updateTime"),
-    DEL("del");
-
-    private final String annoType;
-
-    AnnoEnum(String annoType) {
-        this.annoType = annoType;
-    }
-
-    public String getAnnoType() {
-        return annoType;
-    }
-}

+ 0 - 22
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/enums/FieldEnum.java

@@ -1,22 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.enums;
-
-import java.security.Timestamp;
-import java.util.Date;
-
-public enum FieldEnum {
-
-    STRING(String.class),
-    LONG(Long.class),
-    DATE(Date.class),
-    TIMESTAMP(Timestamp.class);
-
-    private Class fieldType;
-
-    FieldEnum(Class fieldType) {
-        this.fieldType = fieldType;
-    }
-
-    public Class getFieldType() {
-        return fieldType;
-    }
-}

+ 0 - 163
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/interceptor/interceptor/StuffInterceptor.java

@@ -1,163 +0,0 @@
-package com.github.jfcloud.gene.common.interceptor.interceptor;
-
-import cn.hutool.core.util.ReflectUtil;
-import com.github.jfcloud.gene.common.entity.BaseEntity;
-import com.github.jfcloud.gene.common.interceptor.anno.AutoStuff;
-import com.github.jfcloud.gene.common.interceptor.enums.AnnoEnum;
-import com.github.jfcloud.gene.common.util.UserUtil;
-import lombok.extern.log4j.Log4j2;
-import org.apache.ibatis.executor.Executor;
-import org.apache.ibatis.mapping.MappedStatement;
-import org.apache.ibatis.mapping.SqlCommandType;
-import org.apache.ibatis.plugin.Interceptor;
-import org.apache.ibatis.plugin.Intercepts;
-import org.apache.ibatis.plugin.Invocation;
-import org.apache.ibatis.plugin.Signature;
-import org.springframework.stereotype.Component;
-
-import java.lang.reflect.Field;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-@Log4j2
-@Component
-@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
-public class StuffInterceptor implements Interceptor {
-
-    @Override
-    public Object intercept(Invocation invocation) throws Throwable {
-        if (invocation.getTarget() instanceof Executor && invocation.getArgs().length == 2) {
-
-            final Executor executor = (Executor) invocation.getTarget();
-            // 获取第一个参数
-            final MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
-            final Object paramObj = invocation.getArgs()[1];
-
-            if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
-                return this.executeInsert(executor, ms, paramObj);
-            }
-
-            if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
-                return this.executeUpdate(executor, ms, paramObj);
-            }
-        }
-        return invocation.proceed();
-    }
-
-    /**
-     * 新增操作
-     */
-    private Object executeInsert(final Executor executor, final MappedStatement ms, final Object paramObj) throws Exception {
-
-        // 获取所有字段
-        final Field[] fields = ReflectUtil.getFields(paramObj.getClass());
-        for (final Field field : fields) {
-            // 设置该字段对象的可访问标志
-            field.setAccessible(true);
-            // 判断字段是否有我们的AutoStuff注解
-            if (field.isAnnotationPresent(AutoStuff.class)) {
-                // 获取该注解
-                AutoStuff autoStuff = field.getAnnotation(AutoStuff.class);
-                // 获取注解里写的annoType
-                String annoType = autoStuff.annoType().getAnnoType();
-                // 获取原来的值
-                Object originalValue = field.get(paramObj);
-                if (Objects.isNull(originalValue)) {
-                    continue;
-                }
-
-                // 先进行字段类型判断,再判断归属,所有信息都是通过operInfo接口获取的
-                if (AnnoEnum.TENANT_ID.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, UserUtil.getTenantId());
-                    continue;
-                }
-                if (AnnoEnum.DEPT_ID.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, UserUtil.getDeptId());
-                    continue;
-                }
-                if (AnnoEnum.CREATE_BY.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, UserUtil.getUserName());
-                    continue;
-                }
-                if (AnnoEnum.CREATE_TIME.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, new Date());
-                    continue;
-                }
-                if (AnnoEnum.UPDATE_BY.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, UserUtil.getUserName());
-                    continue;
-                }
-                if (AnnoEnum.UPDATE_TIME.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, new Date());
-                    continue;
-                }
-            }
-        }
-        return executor.update(ms, paramObj);
-    }
-
-    /**
-     * @Title: executeUpdate
-     * @Description: 编辑操作
-     * @param: executor
-     * @param: ms
-     * @param: paramObj
-     * @param: user
-     * @return:
-     * @author: hejin
-     * @date: 2022/8/15 11:05
-     */
-    @SuppressWarnings({"unchecked"})
-    private Object executeUpdate(final Executor executor, final MappedStatement ms, final Object paramObj) throws Exception {
-        if (paramObj instanceof Map) {
-            Map<String, Object> map = (Map<String, Object>) paramObj;
-            Map<String, Object> newParam = new HashMap<>(map.size());
-            for (Map.Entry<String, Object> entry : map.entrySet()) {
-                String key = entry.getKey();
-                Object value = entry.getValue();
-                if (Objects.isNull(value)) {
-                    continue;
-                }
-                if (!(value instanceof BaseEntity)) {
-                    newParam.put(key, value);
-                    continue;
-                }
-
-                final Field[] fields = ReflectUtil.getFields(value.getClass());
-                for (final Field field : fields) {
-                    field.setAccessible(true);
-                    AutoStuff autoStuff = field.getAnnotation(AutoStuff.class);
-                    if (autoStuff != null) {
-                        String annoType = autoStuff.annoType().getAnnoType();
-                        if (AnnoEnum.UPDATE_BY.getAnnoType().equals(annoType)) {
-                            field.set(value, UserUtil.getUserName());
-                        }
-                        if (AnnoEnum.UPDATE_TIME.getAnnoType().equals(annoType)) {
-                            field.set(value, new Date());
-                        }
-                    }
-                }
-                newParam.put(key, value);
-            }
-            return executor.update(ms, newParam);
-        }
-
-        final Field[] fields = ReflectUtil.getFields(paramObj.getClass());
-        for (final Field field : fields) {
-            field.setAccessible(true);
-            AutoStuff autoStuff = field.getAnnotation(AutoStuff.class);
-            if (autoStuff != null) {
-                String annoType = autoStuff.annoType().getAnnoType();
-                if (AnnoEnum.UPDATE_BY.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, UserUtil.getUserName());
-                }
-                if (AnnoEnum.UPDATE_TIME.getAnnoType().equals(annoType)) {
-                    field.set(paramObj, new Date());
-                }
-            }
-        }
-        return executor.update(ms, paramObj);
-    }
-}

+ 4 - 1
jfcloud-gene-common/src/main/java/com/github/jfcloud/gene/common/util/UserUtil.java

@@ -1,5 +1,6 @@
 package com.github.jfcloud.gene.common.util;
 package com.github.jfcloud.gene.common.util;
 
 
+import cn.hutool.core.collection.CollUtil;
 import com.github.jfcloud.common.core.base.JfcloudUserInfo;
 import com.github.jfcloud.common.core.base.JfcloudUserInfo;
 import com.github.jfcloud.common.security.service.JfcloudUser;
 import com.github.jfcloud.common.security.service.JfcloudUser;
 import com.github.jfcloud.common.security.util.SecurityUtils;
 import com.github.jfcloud.common.security.util.SecurityUtils;
@@ -7,6 +8,7 @@ import lombok.RequiredArgsConstructor;
 import lombok.extern.log4j.Log4j2;
 import lombok.extern.log4j.Log4j2;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.List;
 
 
 @Component
 @Component
@@ -35,7 +37,8 @@ public class UserUtil {
     }
     }
 
 
     public static Long getDeptId() {
     public static Long getDeptId() {
-        return getCurrentUser().getDeptId();
+        ArrayList<Long> deptIds = getCurrentUser().getDeptIds();
+        return CollUtil.isEmpty(deptIds) ? null : deptIds.get(0);
     }
     }
 
 
     public static Long getTenantId() {
     public static Long getTenantId() {