Pārlūkot izejas kodu

Merge pull request #4179 from nieqiurong/20211226165614

增强Service层删除功能
qmdx 3 gadi atpakaļ
vecāks
revīzija
f65bcd8f95

+ 1 - 1
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/mapper/BaseMapper.java

@@ -121,7 +121,7 @@ public interface BaseMapper<T> extends Mapper<T> {
     int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
 
 
     /**
     /**
-     * 删除(根据ID 批量删除)
+     * 删除(根据ID或实体 批量删除)
      *
      *
      * @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
      * @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
      */
      */

+ 21 - 0
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/metadata/TableInfo.java

@@ -30,6 +30,7 @@ import org.apache.ibatis.mapping.ResultMapping;
 import org.apache.ibatis.reflection.Reflector;
 import org.apache.ibatis.reflection.Reflector;
 import org.apache.ibatis.session.Configuration;
 import org.apache.ibatis.session.Configuration;
 
 
+import java.lang.reflect.Constructor;
 import java.util.*;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Predicate;
 import java.util.function.Predicate;
@@ -546,4 +547,24 @@ public class TableInfo implements Constants {
         }
         }
     }
     }
 
 
+    /**
+     * 创建实例
+     *
+     * @param <T> 泛型
+     * @return 初始化实例
+     * @since 3.5.0
+     */
+    @SuppressWarnings("unchecked")
+    public <T> T newInstance() {
+        Constructor<?> defaultConstructor = reflector.getDefaultConstructor();
+        if (!defaultConstructor.isAccessible()) {
+            defaultConstructor.setAccessible(true);
+        }
+        try {
+            return (T) defaultConstructor.newInstance();
+        } catch (ReflectiveOperationException e) {
+            throw ExceptionUtils.mpe(e);
+        }
+    }
+
 }
 }

+ 9 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/metadata/TableInfoHelperTest.java

@@ -247,4 +247,13 @@ class TableInfoHelperTest {
         @TableField("`name`")
         @TableField("`name`")
         private Long name;
         private Long name;
     }
     }
+
+    @Test
+    void testNewInstance() throws ReflectiveOperationException {
+        TableInfo tableInfo = TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), ModelOne.class);
+        ModelOne entity = tableInfo.newInstance();
+        tableInfo.setPropertyValue(entity, tableInfo.getKeyColumn(), 1L);
+        assertThat(entity.id).isNotNull().isEqualTo(1L);
+    }
+
 }
 }

+ 40 - 2
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/IService.java

@@ -108,6 +108,18 @@ public interface IService<T> {
         return SqlHelper.retBool(getBaseMapper().deleteById(id));
         return SqlHelper.retBool(getBaseMapper().deleteById(id));
     }
     }
 
 
+    /**
+     * 根据 ID 删除
+     *
+     * @param id      主键(类型必须与实体类型字段保持一致)
+     * @param useFill 是否启用填充(为true的情况,会将入参转换实体进行delete删除)
+     * @return 删除结果
+     * @since 3.5.0
+     */
+    default boolean removeById(Serializable id, boolean useFill) {
+        throw new UnsupportedOperationException("不支持的方法!");
+    }
+
     /**
     /**
      * 根据实体(ID)删除
      * 根据实体(ID)删除
      *
      *
@@ -140,13 +152,39 @@ public interface IService<T> {
     /**
     /**
      * 删除(根据ID 批量删除)
      * 删除(根据ID 批量删除)
      *
      *
-     * @param idList 主键ID列表
+     * @param list 主键ID或实体列表
      */
      */
     default boolean removeByIds(Collection<?> idList) {
     default boolean removeByIds(Collection<?> idList) {
         if (CollectionUtils.isEmpty(idList)) {
         if (CollectionUtils.isEmpty(idList)) {
             return false;
             return false;
         }
         }
-        return SqlHelper.retBool(getBaseMapper().deleteBatchIds(idList));
+        return SqlHelper.retBool(getBaseMapper().deleteBatchIds(list));
+    }
+
+    /**
+     * 批量删除(jdbc批量提交)
+     *
+     * @param list    主键ID或实体列表(主键ID类型必须与实体类型字段保持一致)
+     * @param useFill 是否启用填充(为true的情况,会将入参转换实体进行delete删除)
+     * @return 删除结果
+     * @since 3.5.0
+     */
+    @Transactional(rollbackFor = Exception.class)
+    default boolean removeBatchByIds(Collection<?> list, boolean useFill) {
+        return removeBatchByIds(list, DEFAULT_BATCH_SIZE, useFill);
+    }
+
+    /**
+     * 批量删除(jdbc批量提交)
+     *
+     * @param list      主键ID或实体列表
+     * @param batchSize 批次大小
+     * @param useFill   是否启用填充(为true的情况,会将入参转换实体进行delete删除)
+     * @return 删除结果
+     * @since 3.5.0
+     */
+    default boolean removeBatchByIds(Collection<?> list, int batchSize, boolean useFill) {
+        throw new UnsupportedOperationException("不支持的方法!");
     }
     }
 
 
     /**
     /**

+ 31 - 0
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/impl/ServiceImpl.java

@@ -253,4 +253,35 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
         return executeBatch(list, DEFAULT_BATCH_SIZE, consumer);
         return executeBatch(list, DEFAULT_BATCH_SIZE, consumer);
     }
     }
 
 
+    @Override
+    public boolean removeById(Serializable id, boolean useFill) {
+        if (useFill && !entityClass.isAssignableFrom(id.getClass())) {
+            TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
+            T instance = tableInfo.newInstance();
+            tableInfo.setPropertyValue(instance, tableInfo.getKeyProperty(), id);
+            return removeById(instance);
+        }
+        return removeById(id);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public boolean removeBatchByIds(Collection<?> list, int batchSize, boolean useFill) {
+        String sqlStatement = getSqlStatement(SqlMethod.DELETE_BY_ID);
+        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
+        return executeBatch(list, batchSize, (sqlSession, e) -> {
+            if (useFill) {
+                if (entityClass.isAssignableFrom(e.getClass())) {
+                    sqlSession.update(sqlStatement, e);
+                } else {
+                    T instance = tableInfo.newInstance();
+                    tableInfo.setPropertyValue(instance, tableInfo.getKeyProperty(), e);
+                    sqlSession.update(sqlStatement, instance);
+                }
+            } else {
+                sqlSession.update(sqlStatement, e);
+            }
+        });
+    }
+
 }
 }

+ 12 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/h2/H2UserTest.java

@@ -556,4 +556,16 @@ class H2UserTest extends BaseTest {
         Assertions.assertTrue(userService.page(page, Wrappers.<H2User>lambdaQuery()
         Assertions.assertTrue(userService.page(page, Wrappers.<H2User>lambdaQuery()
             .orderByDesc(H2User::getTestId)).getPages() > 0);
             .orderByDesc(H2User::getTestId)).getPages() > 0);
     }
     }
+
+    @Test
+    void testDeleteByFill() {
+        H2User h2User = new H2User(3L, "test");
+        userService.removeById(1L, true);
+        userService.removeById(1L, false);
+        userService.removeById(h2User, true);
+        userService.removeById(h2User, false);
+        userService.removeBatchByIds(Arrays.asList(1L, 2L, h2User), true);
+        userService.removeBatchByIds(Arrays.asList(1L, 2L, h2User), false);
+    }
+
 }
 }