Przeglądaj źródła

Merge branch 'baomidou:3.0' into 3.0

胡洋 3 lat temu
rodzic
commit
3bf612c98b

+ 14 - 2
README-zh.md

@@ -1,5 +1,5 @@
 <p align="center">
-  <a href="https://github.com/baomidou/mybatis-plus">
+  <a href="https://github.com/baomidou/mybatis-plus" target="_blank">
    <img alt="Mybatis-Plus-Logo" src="https://raw.githubusercontent.com/baomidou/logo/master/mybatis-plus-logo-new-mini.png">
   </a>
 </p>
@@ -24,7 +24,19 @@
 
 Mybatis 增强工具包 - 只做增强不做改变,简化`CRUD`操作
 
-技术讨论 QQ 群 : 183066216 、  576493122 🈵  、  648281531 🈵 、  643509491 🈵
+添加 `微信 wx153666` 备注进 mp 群
+
+# 特别用户
+
+<p>
+  <a href="https://www.diboot.com/?from=mp" target="_blank">
+   <img alt="Mybatis-Plus-Logo" src="https://www.diboot.com/diboot_slogon.png" width="210px" height="75px">
+  </a>
+  <a href="http://aizuda.com/?from=mp" target="_blank">
+   <img alt="Mybatis-Plus-Logo" src="https://baomidou.com/img/aizuda.png" width="210px" height="75px">
+  </a>
+</p>
+
 
 # 优点 | Advantages
 

+ 13 - 0
README.md

@@ -24,6 +24,19 @@
 
 [企业版 Mybatis-Mate 高级特性](https://gitee.com/baomidou/mybatis-mate-examples)
 
+添加 `微信 wx153666` 备注进 mp 群
+
+# Special user
+
+<p>
+  <a href="https://www.diboot.com/?from=mp" target="_blank">
+   <img alt="Mybatis-Plus-Logo" src="https://www.diboot.com/diboot_slogon.png" width="210px" height="75px">
+  </a>
+  <a href="http://aizuda.com/?from=mp" target="_blank">
+   <img alt="Mybatis-Plus-Logo" src="https://baomidou.com/img/aizuda.png" width="210px" height="75px">
+  </a>
+</p>
+
 ## What is MyBatis-Plus?
 
 MyBatis-Plus is an powerful enhanced toolkit of MyBatis for simplify development. This toolkit provides some efficient, useful, out-of-the-box features for MyBatis, use it can effectively save your development time.

+ 1 - 2
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/MybatisMapperRegistry.java

@@ -50,7 +50,7 @@ public class MybatisMapperRegistry extends MapperRegistry {
         MybatisMapperProxyFactory<T> mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.get(type);
         if (mapperProxyFactory == null) {
             mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.entrySet().stream()
-                .filter(t -> t.getKey().getName().equals(type.getName())).findFirst()
+                .filter(t -> t.getKey().getName().equals(type.getName())).findFirst().map(Map.Entry::getValue)
                 .orElseThrow(() -> new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry."));
         }
         try {
@@ -69,7 +69,6 @@ public class MybatisMapperRegistry extends MapperRegistry {
      * 清空 Mapper 缓存信息
      */
     protected <T> void removeMapper(Class<T> type) {
-        // TODO
         knownMappers.entrySet().stream().filter(t -> t.getKey().getName().equals(type.getName()))
             .findFirst().ifPresent(t -> knownMappers.remove(t.getKey()));
     }

+ 4 - 6
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/methods/Insert.java

@@ -65,12 +65,10 @@ public class Insert extends AbstractMethod {
                 keyGenerator = Jdbc3KeyGenerator.INSTANCE;
                 keyProperty = tableInfo.getKeyProperty();
                 keyColumn = tableInfo.getKeyColumn();
-            } else {
-                if (null != tableInfo.getKeySequence()) {
-                    keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, builderAssistant);
-                    keyProperty = tableInfo.getKeyProperty();
-                    keyColumn = tableInfo.getKeyColumn();
-                }
+            } else if (null != tableInfo.getKeySequence()) {
+                keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, builderAssistant);
+                keyProperty = tableInfo.getKeyProperty();
+                keyColumn = tableInfo.getKeyColumn();
             }
         }
         String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);

+ 26 - 30
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/toolkit/SimpleQuery.java

@@ -1,21 +1,27 @@
 package com.baomidou.mybatisplus.extension.toolkit;
 
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
-import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
-import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
-import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
-import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
-import org.apache.ibatis.session.SqlSession;
-import org.mybatis.spring.SqlSessionUtils;
-
-import java.util.*;
-import java.util.function.*;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BinaryOperator;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
 import java.util.stream.Collector;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import java.util.stream.StreamSupport;
 
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
+
 /**
  * simple-query 让简单的查询更简单
  *
@@ -109,7 +115,7 @@ public class SimpleQuery {
      * ignore
      */
     @SafeVarargs
-    public static <T, K, D, A, M extends Map<K, D>> M group(LambdaQueryWrapper<T> wrapper, SFunction<T, K> sFunction, Collector<? super T, A, D> downstream, Consumer<T>... peeks) {
+    public static <T, K, D, A> Map<K, D> group(LambdaQueryWrapper<T> wrapper, SFunction<T, K> sFunction, Collector<T, A, D> downstream, Consumer<T>... peeks) {
         return listGroupBy(selectList(getType(sFunction), wrapper), sFunction, downstream, false, peeks);
     }
 
@@ -125,11 +131,10 @@ public class SimpleQuery {
      * @param <K>        实体中的分组依据对应类型,也是Map中key的类型
      * @param <D>        下游操作对应返回类型,也是Map中value的类型
      * @param <A>        下游操作在进行中间操作时对应类型
-     * @param <M>        最后返回结果Map类型
      * @return Map<实体中的属性, List < 实体>>
      */
     @SafeVarargs
-    public static <T, K, D, A, M extends Map<K, D>> M group(LambdaQueryWrapper<T> wrapper, SFunction<T, K> sFunction, Collector<? super T, A, D> downstream, boolean isParallel, Consumer<T>... peeks) {
+    public static <T, K, D, A> Map<K, D> group(LambdaQueryWrapper<T> wrapper, SFunction<T, K> sFunction, Collector<T, A, D> downstream, boolean isParallel, Consumer<T>... peeks) {
         return listGroupBy(selectList(getType(sFunction), wrapper), sFunction, downstream, isParallel, peeks);
     }
 
@@ -199,7 +204,7 @@ public class SimpleQuery {
      * ignore
      */
     @SafeVarargs
-    public static <T, K, D, A, M extends Map<K, D>> M listGroupBy(List<T> list, SFunction<T, K> sFunction, Collector<? super T, A, D> downstream, Consumer<T>... peeks) {
+    public static <T, K, D, A> Map<K, D> listGroupBy(List<T> list, SFunction<T, K> sFunction, Collector<T, A, D> downstream, Consumer<T>... peeks) {
         return listGroupBy(list, sFunction, downstream, false, peeks);
     }
 
@@ -215,14 +220,13 @@ public class SimpleQuery {
      * @param <K>        实体中的分组依据对应类型,也是Map中key的类型
      * @param <D>        下游操作对应返回类型,也是Map中value的类型
      * @param <A>        下游操作在进行中间操作时对应类型
-     * @param <M>        最后返回结果Map类型
      * @return Map<实体中的属性, List < 实体>>
      */
     @SafeVarargs
     @SuppressWarnings("unchecked")
-    public static <T, K, D, A, M extends Map<K, D>> M listGroupBy(List<T> list, SFunction<T, K> sFunction, Collector<? super T, A, D> downstream, boolean isParallel, Consumer<T>... peeks) {
+    public static <T, K, D, A> Map<K, D> listGroupBy(List<T> list, SFunction<T, K> sFunction, Collector<T, A, D> downstream, boolean isParallel, Consumer<T>... peeks) {
         boolean hasFinished = downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH);
-        return peekStream(list, isParallel, peeks).collect(new Collector<T, HashMap<K, A>, M>() {
+        return peekStream(list, isParallel, peeks).collect(new Collector<T, HashMap<K, A>, Map<K, D>>() {
             @Override
             public Supplier<HashMap<K, A>> supplier() {
                 return HashMap::new;
@@ -249,11 +253,11 @@ public class SimpleQuery {
             }
 
             @Override
-            public Function<HashMap<K, A>, M> finisher() {
-                return hasFinished ? i -> (M) i : intermediate -> {
+            public Function<HashMap<K, A>, Map<K, D>> finisher() {
+                return hasFinished ? i -> (Map<K, D>) i : intermediate -> {
                     intermediate.replaceAll((k, v) -> (A) downstream.finisher().apply(v));
                     @SuppressWarnings("unchecked")
-                    M castResult = (M) intermediate;
+                    Map<K, D> castResult = (Map<K, D>) intermediate;
                     return castResult;
                 };
             }
@@ -317,15 +321,7 @@ public class SimpleQuery {
      * @return 查询列表结果
      */
     public static <E> List<E> selectList(Class<E> entityClass, LambdaQueryWrapper<E> wrapper) {
-        SqlSession sqlSession = SqlHelper.sqlSession(entityClass);
-        List<E> result;
-        try {
-            BaseMapper<E> userMapper = SqlHelper.getMapper(entityClass, sqlSession);
-            result = userMapper.selectList(wrapper);
-        } finally {
-            SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(entityClass));
-        }
-        return result;
+        return SqlHelper.execute(entityClass, m -> m.selectList(wrapper));
     }
 
 }

+ 21 - 33
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/toolkit/SqlHelper.java

@@ -20,11 +20,11 @@ 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.*;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
 import lombok.SneakyThrows;
 import org.apache.ibatis.exceptions.PersistenceException;
 import org.apache.ibatis.logging.Log;
 import org.apache.ibatis.reflection.ExceptionUtil;
-import org.apache.ibatis.session.Configuration;
 import org.apache.ibatis.session.ExecutorType;
 import org.apache.ibatis.session.SqlSession;
 import org.apache.ibatis.session.SqlSessionFactory;
@@ -264,33 +264,6 @@ public final class SqlHelper {
         return mapper.getName() + StringPool.DOT + sqlMethod.getMethod();
     }
 
-
-    /**
-     * 通过entityClass获取Mapper
-     *
-     * @param entityClass 实体
-     * @param <T>         实体类型
-     * @return Mapper
-     * @deprecated 使用后未释放连接 {@link SqlHelper#getMapper(Class, SqlSession)}
-     */
-    @SuppressWarnings("unchecked")
-    @Deprecated
-    public static <T> BaseMapper<T> getMapper(Class<T> entityClass) {
-        Optional.ofNullable(entityClass).orElseThrow(() -> ExceptionUtils.mpe("entityClass can't be null!"));
-        TableInfo tableInfo = Optional.ofNullable(TableInfoHelper.getTableInfo(entityClass)).orElseThrow(() -> ExceptionUtils.mpe("Can not find TableInfo from Class: \"%s\".", entityClass.getName()));
-        String namespace = tableInfo.getCurrentNamespace();
-
-        Configuration configuration = tableInfo.getConfiguration();
-        SqlSession sqlSession = sqlSession(entityClass);
-        BaseMapper<T> mapper;
-        try {
-            mapper = (BaseMapper<T>) configuration.getMapper(Class.forName(namespace), sqlSession);
-        } catch (ClassNotFoundException e) {
-            throw ExceptionUtils.mpe(e);
-        }
-        return mapper;
-    }
-
     /**
      * 通过entityClass获取Mapper,记得要释放连接
      * 例: {@code
@@ -308,13 +281,28 @@ public final class SqlHelper {
      */
     @SuppressWarnings("unchecked")
     public static <T> BaseMapper<T> getMapper(Class<T> entityClass, SqlSession sqlSession) {
-        Optional.ofNullable(entityClass).orElseThrow(() -> ExceptionUtils.mpe("entityClass can't be null!"));
+        Assert.notNull(entityClass, "entityClass can't be null!");
         TableInfo tableInfo = Optional.ofNullable(TableInfoHelper.getTableInfo(entityClass)).orElseThrow(() -> ExceptionUtils.mpe("Can not find TableInfo from Class: \"%s\".", entityClass.getName()));
+        Class<?> mapperClass = ClassUtils.toClassConfident(tableInfo.getCurrentNamespace());
+        return (BaseMapper<T>) tableInfo.getConfiguration().getMapper(mapperClass, sqlSession);
+    }
+
+    /**
+     * 通过entityClass获取BaseMapper,再传入lambda使用该mapper,本方法自动释放链接
+     *
+     * @param entityClass 实体类
+     * @param sFunction   lambda操作,例如 {@code m->m.selectList(wrapper)}
+     * @param <T>         实体类的类型
+     * @param <R>         返回值类型
+     * @return 返回lambda执行结果
+     */
+    public static <T, R> R execute(Class<T> entityClass, SFunction<BaseMapper<T>, R> sFunction) {
+        SqlSession sqlSession = SqlHelper.sqlSession(entityClass);
         try {
-            Configuration configuration = tableInfo.getConfiguration();
-            return (BaseMapper<T>) configuration.getMapper(Class.forName(tableInfo.getCurrentNamespace()), sqlSession);
-        } catch (ClassNotFoundException e) {
-            throw ExceptionUtils.mpe(e);
+            BaseMapper<T> baseMapper = SqlHelper.getMapper(entityClass, sqlSession);
+            return sFunction.apply(baseMapper);
+        } finally {
+            SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(entityClass));
         }
     }
 }

+ 6 - 7
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/toolkit/SimpleQueryTest.java

@@ -1,10 +1,8 @@
 package com.baomidou.mybatisplus.test.toolkit;
 
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.toolkit.Assert;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
-import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
 import com.baomidou.mybatisplus.test.BaseDbTest;
 import com.baomidou.mybatisplus.test.rewrite.Entity;
 import com.baomidou.mybatisplus.test.rewrite.EntityMapper;
@@ -55,11 +53,12 @@ public class SimpleQueryTest extends BaseDbTest<EntityMapper> {
     @Test
     public void testGroup() {
         // 我需要相同名字的用户的分为一组,再造一条数据
-        BaseMapper<Entity> mapper = SqlHelper.getMapper(Entity.class);
-        Entity entity = new Entity();
-        entity.setId(3L);
-        entity.setName("ruben");
-        mapper.insert(entity);
+        doTestAutoCommit(m -> {
+            Entity entity = new Entity();
+            entity.setId(3L);
+            entity.setName("ruben");
+            m.insert(entity);
+        });
 
         // 简单查询
         Map<String, List<Entity>> nameUsersMap = SimpleQuery.group(Wrappers.lambdaQuery(), Entity::getName);

+ 17 - 8
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/toolkit/SqlHelperTest.java

@@ -1,15 +1,16 @@
 package com.baomidou.mybatisplus.test.toolkit;
 
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import com.baomidou.mybatisplus.core.toolkit.Assert;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
 import com.baomidou.mybatisplus.test.BaseDbTest;
 import com.baomidou.mybatisplus.test.rewrite.Entity;
 import com.baomidou.mybatisplus.test.rewrite.EntityMapper;
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.List;
 
 /**
  * SqlHelper 工具类测试
@@ -20,9 +21,17 @@ import java.util.List;
 public class SqlHelperTest extends BaseDbTest<EntityMapper> {
 
     @Test
-    public void testGetMapper() {
-        BaseMapper<Entity> mapper = SqlHelper.getMapper(Entity.class);
-        System.out.println(mapper.selectList(Wrappers.lambdaQuery()));
+    public void testGetMapperAndExecute() {
+
+        List<Entity> entityList = SqlHelper.execute(Entity.class, m -> m.selectList(Wrappers.lambdaQuery()));
+
+        Entity ruben = new Entity();
+        ruben.setId(1L);
+        ruben.setName("ruben");
+        Entity aChao = new Entity();
+        aChao.setId(2L);
+        aChao.setName("a chao");
+        Assert.isTrue(entityList.equals(Arrays.asList(ruben, aChao)), "There is something wrong,please check your environment!");
     }
 
     @Override