Ver Fonte

优化可更新实体对象默认值自动填充逻辑

woody há 11 meses atrás
pai
commit
fcae9b7a04

+ 0 - 36
framework-database/src/main/java/com/chelvc/framework/database/context/DatabaseContextHolder.java

@@ -46,7 +46,6 @@ import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.chelvc.framework.base.context.ApplicationContextHolder;
-import com.chelvc.framework.base.context.SessionContextHolder;
 import com.chelvc.framework.base.util.SpringUtils;
 import com.chelvc.framework.common.function.Executor;
 import com.chelvc.framework.common.function.Handler;
@@ -64,10 +63,7 @@ import com.chelvc.framework.common.util.StringUtils;
 import com.chelvc.framework.database.annotation.Confidential;
 import com.chelvc.framework.database.annotation.Unique;
 import com.chelvc.framework.database.config.DatabaseProperties;
-import com.chelvc.framework.database.entity.Creatable;
-import com.chelvc.framework.database.entity.Deletable;
 import com.chelvc.framework.database.entity.Entity;
-import com.chelvc.framework.database.entity.Updatable;
 import com.chelvc.framework.database.support.EventService;
 import com.google.common.collect.Maps;
 import lombok.NonNull;
@@ -636,38 +632,6 @@ public final class DatabaseContextHolder {
         });
     }
 
-    /**
-     * 初始化实体默认属性值
-     *
-     * @param entity 数据实体
-     */
-    public static void initializeEntityDefaultValue(@NonNull Entity<?> entity) {
-        if (entity instanceof Creatable) {
-            Creatable<?> creatable = (Creatable<?>) entity;
-            if (creatable.getCreator() == null) {
-                creatable.setCreator(SessionContextHolder.getId());
-            }
-            if (creatable.getCreateTime() == null) {
-                creatable.setCreateTime(new Date());
-            }
-        }
-        if (entity instanceof Updatable) {
-            Updatable<?> updatable = (Updatable<?>) entity;
-            if (updatable.getUpdater() == null) {
-                updatable.setUpdater(SessionContextHolder.getId());
-            }
-            if (updatable.getUpdateTime() == null) {
-                updatable.setUpdateTime(new Date());
-            }
-        }
-        if (entity instanceof Deletable) {
-            Deletable<?> deletable = (Deletable<?>) entity;
-            if (deletable.getDeleted() == null) {
-                deletable.setDeleted(false);
-            }
-        }
-    }
-
     /**
      * 初始化唯一约束查询对象
      *

+ 2 - 2
framework-database/src/main/java/com/chelvc/framework/database/interceptor/DeletedExcludeInterceptor.java

@@ -19,7 +19,7 @@ public class DeletedExcludeInterceptor implements TenantLineHandler {
     /**
      * 删除标记字段名称
      */
-    public static final String DELETED_COLUMN_NAME = "deleted";
+    public static final String COLUMN = "deleted";
 
     /**
      * 未删除值对象
@@ -43,7 +43,7 @@ public class DeletedExcludeInterceptor implements TenantLineHandler {
 
     @Override
     public String getTenantIdColumn() {
-        return DELETED_COLUMN_NAME;
+        return COLUMN;
     }
 
     @Override

+ 44 - 13
framework-database/src/main/java/com/chelvc/framework/database/interceptor/PropertyUpdateInterceptor.java

@@ -2,17 +2,22 @@ package com.chelvc.framework.database.interceptor;
 
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.stream.Collectors;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.chelvc.framework.base.context.SessionContextHolder;
 import com.chelvc.framework.common.exception.ParameterInvalidException;
 import com.chelvc.framework.common.util.ObjectUtils;
 import com.chelvc.framework.database.context.DatabaseContextHolder;
 import com.chelvc.framework.database.context.UniqueContext;
+import com.chelvc.framework.database.entity.Creatable;
+import com.chelvc.framework.database.entity.Deletable;
 import com.chelvc.framework.database.entity.Entity;
+import com.chelvc.framework.database.entity.Updatable;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.ibatis.binding.MapperMethod;
 import org.apache.ibatis.cache.CacheKey;
@@ -45,6 +50,36 @@ import org.springframework.stereotype.Component;
                 RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
 })
 public class PropertyUpdateInterceptor implements Interceptor {
+    /**
+     * 初始化实体默认属性值
+     *
+     * @param entity 数据实体
+     */
+    private void initializeDefaultValue(Entity<?> entity) {
+        Date now = new Date();
+        Long operator = SessionContextHolder.getId();
+        if (entity instanceof Creatable) {
+            Creatable<?> creatable = (Creatable<?>) entity;
+            if (creatable.getCreator() == null) {
+                creatable.setCreator(operator);
+            }
+            if (creatable.getCreateTime() == null) {
+                creatable.setCreateTime(now);
+            }
+        }
+        if (entity instanceof Updatable) {
+            Updatable<?> updatable = (Updatable<?>) entity;
+            updatable.setUpdater(operator);
+            updatable.setUpdateTime(now);
+        }
+        if (entity instanceof Deletable) {
+            Deletable<?> deletable = (Deletable<?>) entity;
+            if (deletable.getDeleted() == null) {
+                deletable.setDeleted(false);
+            }
+        }
+    }
+
     /**
      * 数据查询
      *
@@ -71,11 +106,10 @@ public class PropertyUpdateInterceptor implements Interceptor {
      * 数据更新
      *
      * @param invocation 方法调用信息
-     * @param operation  数据更新类型
      * @return 更新结果
      * @throws Throwable 操作异常
      */
-    private Object modify(Invocation invocation, SqlCommandType operation) throws Throwable {
+    private Object modify(Invocation invocation) throws Throwable {
         // 获取更新目标对象实例
         Object object = invocation.getArgs()[1];
         if (object instanceof MapperMethod.ParamMap) {
@@ -94,11 +128,11 @@ public class PropertyUpdateInterceptor implements Interceptor {
         if (object instanceof Collection) {
             ((Collection<?>) object).forEach(entity -> {
                 if (entity instanceof Entity) {
-                    this.modify((Entity<?>) entity, operation);
+                    this.modify((Entity<?>) entity);
                 }
             });
         } else if (object instanceof Entity) {
-            this.modify((Entity<?>) object, operation);
+            this.modify((Entity<?>) object);
         }
         return invocation.proceed();
     }
@@ -106,16 +140,13 @@ public class PropertyUpdateInterceptor implements Interceptor {
     /**
      * 实体信息更新
      *
-     * @param entity    实体对象实例
-     * @param operation 数据更新类型
-     * @param <T>       实体类型
+     * @param entity 实体对象实例
+     * @param <T>    实体类型
      */
     @SuppressWarnings("unchecked")
-    private <T extends Entity<?>> void modify(T entity, SqlCommandType operation) {
-        // 初始化实体新增默认属性值
-        if (operation == SqlCommandType.INSERT) {
-            DatabaseContextHolder.initializeEntityDefaultValue(entity);
-        }
+    private <T extends Entity<?>> void modify(T entity) {
+        // 初始化实体默认属性值
+        this.initializeDefaultValue(entity);
 
         // 设置加密属性值
         Class<T> clazz = (Class<T>) entity.getClass();
@@ -169,7 +200,7 @@ public class PropertyUpdateInterceptor implements Interceptor {
         if (operation == SqlCommandType.SELECT) {
             return this.select(invocation);
         } else if (operation == SqlCommandType.INSERT || operation == SqlCommandType.UPDATE) {
-            return this.modify(invocation, operation);
+            return this.modify(invocation);
         }
         return invocation.proceed();
     }

+ 38 - 35
framework-database/src/main/java/com/chelvc/framework/database/support/EnhanceService.java

@@ -1,16 +1,19 @@
 package com.chelvc.framework.database.support;
 
 import java.util.Collection;
-import java.util.Date;
 import java.util.List;
 import java.util.function.Function;
 
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.conditions.update.Update;
 import com.baomidou.mybatisplus.extension.conditions.query.ChainQuery;
+import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
+import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
 import com.chelvc.framework.base.context.SessionContextHolder;
 import com.chelvc.framework.common.model.Pagination;
 import com.chelvc.framework.common.model.Paging;
-import com.chelvc.framework.common.util.ObjectUtils;
 import com.chelvc.framework.database.context.DatabaseContextHolder;
 import com.chelvc.framework.database.entity.Updatable;
 import lombok.NonNull;
@@ -23,42 +26,42 @@ import lombok.NonNull;
  * @date 2024/3/10
  */
 public interface EnhanceService<T> extends IService<T>, EventService<T> {
-    /**
-     * 根据ID修改实体
-     *
-     * @param entity    实体对象实例
-     * @param modifying 是否需要更新修改信息
-     * @return true/false
-     */
-    default boolean updateById(@NonNull T entity, boolean modifying) {
-        if (modifying && entity instanceof Updatable) {
-            Updatable<?> updatable = (Updatable<?>) entity;
-            updatable.setUpdater(SessionContextHolder.getId());
-            updatable.setUpdateTime(new Date());
-        }
-        return this.updateById(entity);
+    @Override
+    default UpdateChainWrapper<T> update() {
+        Class<?> clazz = this.getEntityClass();
+        return new UpdateChainWrapper<T>(this.getBaseMapper()) {
+            @Override
+            public boolean update(T entity) {
+                if (Updatable.class.isAssignableFrom(clazz)) {
+                    this.setSql("updater = " + SessionContextHolder.getId()).setSql("update_time = now()");
+                }
+                return super.update(entity);
+            }
+        };
     }
 
-    /**
-     * 批量根据ID修改实体
-     *
-     * @param entities  实体对象实例集合
-     * @param modifying 是否需要更新修改信息
-     * @return true/false
-     */
-    default boolean updateBatchById(@NonNull Collection<T> entities, boolean modifying) {
-        if (ObjectUtils.isEmpty(entities)) {
-            return false;
-        } else if (modifying && Updatable.class.isAssignableFrom(this.getEntityClass())) {
-            Date now = new Date();
-            Long operator = SessionContextHolder.getId();
-            entities.forEach(entity -> {
-                Updatable<?> updatable = (Updatable<?>) entity;
-                updatable.setUpdater(operator);
-                updatable.setUpdateTime(now);
-            });
+    @Override
+    default LambdaUpdateChainWrapper<T> lambdaUpdate() {
+        Class<?> clazz = this.getEntityClass();
+        return new LambdaUpdateChainWrapper<T>(this.getBaseMapper()) {
+            @Override
+            public boolean update(T entity) {
+                if (Updatable.class.isAssignableFrom(clazz)) {
+                    this.setSql("updater = " + SessionContextHolder.getId()).setSql("update_time = now()");
+                }
+                return super.update(entity);
+            }
+        };
+    }
+
+    @Override
+    default boolean update(T entity, Wrapper<T> wrapper) {
+        if (wrapper instanceof Update && Updatable.class.isAssignableFrom(this.getEntityClass())) {
+            Update<?, ?> update = (Update<?, ?>) wrapper;
+            update.setSql("updater = " + SessionContextHolder.getId());
+            update.setSql("update_time = now()");
         }
-        return this.updateBatchById(entities);
+        return SqlHelper.retBool(this.getBaseMapper().update(entity, wrapper));
     }
 
     /**