Browse Source

优化新增 getOneOpt 执行方法及测试用例

hubin 2 years ago
parent
commit
cf4fac59f7

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

@@ -169,33 +169,29 @@ public interface BaseMapper<T> extends Mapper<T> {
      * @param queryWrapper 实体对象封装操作类(可以为 null)
      */
     default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
-        List<T> list = this.selectList(queryWrapper);
-        // 抄自 DefaultSqlSession#selectOne
-        if (list.size() == 1) {
-            return list.get(0);
-        } else if (list.size() > 1) {
-            throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
-        } else {
-            return null;
-        }
+        return this.selectOne(queryWrapper, true);
     }
 
     /**
      * 根据 entity 条件,查询一条记录,现在会根据{@code throwEx}参数判断是否抛出异常,如果为false就直接返回一条数据
      * <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常</p>
      *
-     * @param throwEx      boolean 参数,为true如果存在多个结果直接抛出异常
      * @param queryWrapper 实体对象封装操作类(可以为 null)
+     * @param throwEx      boolean 参数,为true如果存在多个结果直接抛出异常
      */
     default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper, boolean throwEx) {
         List<T> list = this.selectList(queryWrapper);
-        if (list.size() == 1) {
+        // 抄自 DefaultSqlSession#selectOne
+        int size = list.size();
+        if (size == 1) {
+            return list.get(0);
+        } else if (size > 1) {
+            if (throwEx) {
+                throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
+            }
             return list.get(0);
-        } else if (list.size() > 0 && throwEx) {
-            throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
-        } else {
-            return list.size() == 0 ? null : list.get(0);
         }
+        return null;
     }
 
     /**

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

@@ -20,12 +20,7 @@ import com.baomidou.mybatisplus.core.enums.SqlMethod;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.metadata.TableInfo;
 import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
-import com.baomidou.mybatisplus.core.toolkit.Assert;
-import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
-import com.baomidou.mybatisplus.core.toolkit.Constants;
-import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
-import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
-import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import com.baomidou.mybatisplus.core.toolkit.*;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
 import org.apache.ibatis.binding.MapperMethod;
@@ -204,18 +199,12 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 
     @Override
     public T getOne(Wrapper<T> queryWrapper, boolean throwEx) {
-        if (throwEx) {
-            return baseMapper.selectOne(queryWrapper);
-        }
-        return SqlHelper.getObject(log, baseMapper.selectList(queryWrapper));
+        return baseMapper.selectOne(queryWrapper, throwEx);
     }
 
     @Override
     public Optional<T> getOneOpt(Wrapper<T> queryWrapper, boolean throwEx) {
-        if (throwEx) {
-            return Optional.ofNullable(baseMapper.selectOne(queryWrapper));
-        }
-        return Optional.ofNullable(SqlHelper.getObject(log, baseMapper.selectList(queryWrapper)));
+        return Optional.ofNullable(baseMapper.selectOne(queryWrapper, throwEx));
     }
 
     @Override

+ 18 - 29
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/h2/H2UserTest.java

@@ -33,16 +33,12 @@ import com.baomidou.mybatisplus.test.h2.enums.AgeEnum;
 import com.baomidou.mybatisplus.test.h2.service.IH2UserService;
 import net.sf.jsqlparser.parser.CCJSqlParserUtil;
 import net.sf.jsqlparser.statement.select.Select;
+import org.apache.ibatis.exceptions.TooManyResultsException;
 import org.apache.ibatis.plugin.Interceptor;
 import org.apache.ibatis.session.Configuration;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.MethodOrderer;
-import org.junit.jupiter.api.Order;
-import org.junit.jupiter.api.RepeatedTest;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.*;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.dao.DataAccessException;
@@ -52,13 +48,7 @@ import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
-import java.util.AbstractList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
 
 /**
  * Mybatis Plus H2 Junit Test
@@ -657,7 +647,7 @@ class H2UserTest extends BaseTest {
 
     @Test
     @Order(26)
-    void testServiceGetNullById() {
+    void testServiceGetOptById() {
         H2User user = new H2User(1L, "Evan");
         userService.save(user);
         Optional<H2User> optional = userService.getOptById(1L);
@@ -666,30 +656,29 @@ class H2UserTest extends BaseTest {
 
     @Test
     @Order(27)
-    void testServiceGetNonNullOne() {
+    void testServiceGetOneOpt() {
         H2User user = new H2User(1L, "David");
         userService.save(user);
-        Optional<H2User> optional = userService.getOneOpt(
-            new LambdaQueryWrapper<H2User>().eq(H2User::getName, "David"));
-        optional.ifPresent(u -> log(u.toString()));
+        userService.getOneOpt(Wrappers.<H2User>lambdaQuery().eq(H2User::getName, "David"))
+            .ifPresent(u -> log(u.toString()));
     }
 
     @Test
     @Order(28)
-    void testServiceGetNonNullOneThrowEx() {
+    void testServiceGetOneOptThrowEx() {
         H2User user1 = new H2User(1L, "test1");
         H2User user2 = new H2User(2L, "test1");
         List<H2User> h2Users = Arrays.asList(user1, user2);
         userService.saveBatch(h2Users);
-//        Optional<H2User> optional = userService.getNonNullOne(
-//            new LambdaQueryWrapper<H2User>().eq(H2User::getName, "test1"), true);
-        Optional<H2User> optional1 = userService.getOneOpt(
-            new LambdaQueryWrapper<H2User>().eq(H2User::getName, "test1"), false);
-        Optional<H2User> optional2 = userService.getOneOpt(
-            new LambdaQueryWrapper<H2User>().eq(H2User::getName, "test"), false);
-
-//        optional.ifPresent(u -> log(u.toString()));
-        optional1.ifPresent(u -> log(u.toString()));
-        optional2.ifPresent(u -> log(u.toString()));
+
+        userService.getOneOpt(new LambdaQueryWrapper<H2User>().eq(H2User::getName, "test1"), false)
+            .ifPresent(u -> log(u.toString()));
+
+        userService.getOneOpt(new LambdaQueryWrapper<H2User>().eq(H2User::getName, "test"), false)
+            .ifPresent(u -> log(u.toString()));
+
+        // 异常情况
+        Assertions.assertThrows(TooManyResultsException.class, () -> userService.getOneOpt(Wrappers.<H2User>lambdaQuery()
+            .like(H2User::getName, "tes")));
     }
 }

+ 0 - 10
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/h2/cache/service/impl/CacheServiceImpl.java

@@ -20,16 +20,6 @@ public class CacheServiceImpl extends ServiceImpl<CacheMapper, CacheModel> imple
         executeBatch(idList, (sqlSession, id) -> sqlSession.delete(sqlStatement, id));
     }
 
-//    @Override
-//    @Transactional
-//    public boolean testCustomSaveOrUpdateBatch() {
-//        CacheModel model1 = new CacheModel();
-//        CacheModel model2 = new CacheModel("旺仔");
-//        //name为空写入,不为空按条件更新
-//        boolean result = saveOrUpdateBatch(Arrays.asList(model1, model2), entity -> entity.getName() == null, (entity) -> new QueryWrapper<CacheModel>().lambda().eq(CacheModel::getName, entity.getName()));
-//        return model1.getId() != null && model2.getId() == null && result;
-//    }
-
     @Override
     @Transactional
     public long testBatchTransactionalClear1() {