Browse Source

[优化] 一大波优化

miemie 6 years ago
parent
commit
5c0850f319

+ 5 - 0
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/MybatisConfiguration.java

@@ -44,6 +44,11 @@ public class MybatisConfiguration extends Configuration {
      */
     protected final MybatisMapperRegistry mybatisMapperRegistry = new MybatisMapperRegistry(this);
 
+//    public MybatisConfiguration(Environment environment) {
+//        this();
+//        this.environment = environment;
+//    }
+
     /**
      * 初始化调用
      */

+ 0 - 1
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/MybatisDefaultParameterHandler.java

@@ -39,7 +39,6 @@ import java.util.*;
  * <p>
  * 自定义 ParameterHandler 重装构造函数,填充插入方法主键 ID
  * </p>
- * TODO: 3.0 优化注解填充 ?   怎么优化?
  *
  * @author hubin
  * @since 2016-03-11

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

@@ -94,7 +94,7 @@ public class MybatisMapperRegistry extends MapperRegistry {
     }
 
     /**
-     * @since 3.2.2
+     * 使用自己的 knownMappers
      */
     @Override
     public Collection<Class<?>> getMappers() {

+ 20 - 26
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/MybatisXMLConfigBuilder.java

@@ -15,14 +15,6 @@
  */
 package com.baomidou.mybatisplus.core;
 
-import java.io.InputStream;
-import java.io.Reader;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.sql.DataSource;
-
 import org.apache.ibatis.builder.BaseBuilder;
 import org.apache.ibatis.builder.BuilderException;
 import org.apache.ibatis.builder.xml.XMLMapperBuilder;
@@ -44,16 +36,16 @@ import org.apache.ibatis.reflection.MetaClass;
 import org.apache.ibatis.reflection.ReflectorFactory;
 import org.apache.ibatis.reflection.factory.ObjectFactory;
 import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
-import org.apache.ibatis.session.AutoMappingBehavior;
-import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
-import org.apache.ibatis.session.Configuration;
-import org.apache.ibatis.session.ExecutorType;
-import org.apache.ibatis.session.LocalCacheScope;
+import org.apache.ibatis.session.*;
 import org.apache.ibatis.transaction.TransactionFactory;
 import org.apache.ibatis.type.JdbcType;
-import org.apache.ibatis.type.TypeHandler;
 
-import com.baomidou.mybatisplus.core.toolkit.StringPool;
+import javax.sql.DataSource;
+import java.io.InputStream;
+import java.io.Reader;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
 
 /**
  * <p>
@@ -66,10 +58,10 @@ import com.baomidou.mybatisplus.core.toolkit.StringPool;
  */
 public class MybatisXMLConfigBuilder extends BaseBuilder {
 
-    private boolean parsed;
     private final XPathParser parser;
-    private String environment;
     private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
+    private boolean parsed;
+    private String environment;
 
     public MybatisXMLConfigBuilder(Reader reader) {
         this(reader, null, null);
@@ -95,8 +87,10 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
         this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
     }
 
+    /**
+     * 使用自己的 MybatisConfiguration
+     */
     private MybatisXMLConfigBuilder(XPathParser parser, String environment, Properties props) {
-        //TODO 自定义 Configuration
         super(new MybatisConfiguration());
         ErrorContext.instance().resource("SQL Mapper Configuration");
         this.configuration.setVariables(props);
@@ -125,6 +119,7 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
             propertiesElement(root.evalNode("properties"));
             Properties settings = settingsAsProperties(root.evalNode("settings"));
             loadCustomVfs(settings);
+            loadCustomLogImpl(settings);
             typeAliasesElement(root.evalNode("typeAliases"));
             pluginElement(root.evalNode("plugins"));
             objectFactoryElement(root.evalNode("objectFactory"));
@@ -159,7 +154,7 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
     private void loadCustomVfs(Properties props) throws ClassNotFoundException {
         String value = props.getProperty("vfsImpl");
         if (value != null) {
-            String[] clazzes = value.split(StringPool.COMMA);
+            String[] clazzes = value.split(",");
             for (String clazz : clazzes) {
                 if (!clazz.isEmpty()) {
                     @SuppressWarnings("unchecked")
@@ -170,6 +165,11 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
         }
     }
 
+    private void loadCustomLogImpl(Properties props) {
+        Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
+        configuration.setLogImpl(logImpl);
+    }
+
     private void typeAliasesElement(XNode parent) {
         if (parent != null) {
             for (XNode child : parent.getChildren()) {
@@ -274,16 +274,11 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
         configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
         configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
         configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
+        configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
         configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
         configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
-        @SuppressWarnings("unchecked")
-        Class<? extends TypeHandler> typeHandler = (Class<? extends TypeHandler>) resolveClass(props.getProperty("defaultEnumTypeHandler"));
-        configuration.setDefaultEnumTypeHandler(typeHandler);
         configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
         configuration.setLogPrefix(props.getProperty("logPrefix"));
-        @SuppressWarnings("unchecked")
-        Class<? extends Log> logImpl = (Class<? extends Log>) resolveClass(props.getProperty("logImpl"));
-        configuration.setLogImpl(logImpl);
         configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
     }
 
@@ -445,5 +440,4 @@ public class MybatisXMLConfigBuilder extends BaseBuilder {
             return environment.equals(id);
         }
     }
-
 }

+ 46 - 37
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/override/PageMapperMethod.java

@@ -15,14 +15,7 @@
  */
 package com.baomidou.mybatisplus.core.override;
 
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.baomidou.mybatisplus.core.metadata.IPage;
 import org.apache.ibatis.annotations.Flush;
 import org.apache.ibatis.annotations.MapKey;
 import org.apache.ibatis.binding.BindingException;
@@ -38,8 +31,14 @@ import org.apache.ibatis.session.ResultHandler;
 import org.apache.ibatis.session.RowBounds;
 import org.apache.ibatis.session.SqlSession;
 
-import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.core.toolkit.StringPool;
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 
 /**
  * <p>
@@ -50,13 +49,12 @@ import com.baomidou.mybatisplus.core.toolkit.StringPool;
  * @since 2018-06-09
  */
 public class PageMapperMethod {
-
-    private final PageMapperMethod.SqlCommand command;
-    private final PageMapperMethod.MethodSignature method;
+    private final SqlCommand command;
+    private final MethodSignature method;
 
     public PageMapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
-        this.command = new PageMapperMethod.SqlCommand(config, mapperInterface, method);
-        this.method = new PageMapperMethod.MethodSignature(config, mapperInterface, method);
+        this.command = new SqlCommand(config, mapperInterface, method);
+        this.method = new MethodSignature(config, mapperInterface, method);
     }
 
     @SuppressWarnings("unchecked")
@@ -95,14 +93,17 @@ public class PageMapperMethod {
                      */
                     if (IPage.class.isAssignableFrom(method.getReturnType()) && args != null
                         && IPage.class.isAssignableFrom(args[0].getClass())) {
-                        List<Object> o = (List<Object>) executeForMany2(sqlSession, args);
-                        result = ((IPage) args[0]).setRecords(o);
+                        result = ((IPage) args[0]).setRecords(executeForIPage(sqlSession, args));
+                        /**
+                         * 这上面
+                         */
                     } else {
                         result = sqlSession.selectOne(command.getName(), param);
+                        if (method.returnsOptional() &&
+                            (result == null || !method.getReturnType().equals(result.getClass()))) {
+                            result = Optional.ofNullable(result);
+                        }
                     }
-                    /**
-                     * 这上面
-                     */
                 }
                 break;
             case FLUSH:
@@ -118,16 +119,12 @@ public class PageMapperMethod {
         return result;
     }
 
-    private <E> Object executeForMany2(SqlSession sqlSession, Object[] args) {
-        List<E> result;
+    /**
+     * IPage 专用
+     */
+    private <E> List<E> executeForIPage(SqlSession sqlSession, Object[] args) {
         Object param = method.convertArgsToSqlCommandParam(args);
-        if (method.hasRowBounds()) {
-            RowBounds rowBounds = method.extractRowBounds(args);
-            result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
-        } else {
-            result = sqlSession.<E>selectList(command.getName(), param);
-        }
-        return result;
+        return sqlSession.selectList(command.getName(), param);
     }
 
     private Object rowCountResult(int rowCount) {
@@ -168,9 +165,9 @@ public class PageMapperMethod {
         Object param = method.convertArgsToSqlCommandParam(args);
         if (method.hasRowBounds()) {
             RowBounds rowBounds = method.extractRowBounds(args);
-            result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
+            result = sqlSession.selectList(command.getName(), param, rowBounds);
         } else {
-            result = sqlSession.<E>selectList(command.getName(), param);
+            result = sqlSession.selectList(command.getName(), param);
         }
         // issue #510 Collections & arrays support
         if (!method.getReturnType().isAssignableFrom(result.getClass())) {
@@ -188,9 +185,9 @@ public class PageMapperMethod {
         Object param = method.convertArgsToSqlCommandParam(args);
         if (method.hasRowBounds()) {
             RowBounds rowBounds = method.extractRowBounds(args);
-            result = sqlSession.<T>selectCursor(command.getName(), param, rowBounds);
+            result = sqlSession.selectCursor(command.getName(), param, rowBounds);
         } else {
-            result = sqlSession.<T>selectCursor(command.getName(), param);
+            result = sqlSession.selectCursor(command.getName(), param);
         }
         return result;
     }
@@ -221,9 +218,9 @@ public class PageMapperMethod {
         Object param = method.convertArgsToSqlCommandParam(args);
         if (method.hasRowBounds()) {
             RowBounds rowBounds = method.extractRowBounds(args);
-            result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey(), rowBounds);
+            result = sqlSession.selectMap(command.getName(), param, method.getMapKey(), rowBounds);
         } else {
-            result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey());
+            result = sqlSession.selectMap(command.getName(), param, method.getMapKey());
         }
         return result;
     }
@@ -258,7 +255,7 @@ public class PageMapperMethod {
                     type = SqlCommandType.FLUSH;
                 } else {
                     throw new BindingException("Invalid bound statement (not found): "
-                        + mapperInterface.getName() + StringPool.DOT + methodName);
+                        + mapperInterface.getName() + "." + methodName);
                 }
             } else {
                 name = ms.getId();
@@ -279,7 +276,7 @@ public class PageMapperMethod {
 
         private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
                                                        Class<?> declaringClass, Configuration configuration) {
-            String statementId = mapperInterface.getName() + StringPool.DOT + methodName;
+            String statementId = mapperInterface.getName() + "." + methodName;
             if (configuration.hasStatement(statementId)) {
                 return configuration.getMappedStatement(statementId);
             } else if (mapperInterface.equals(declaringClass)) {
@@ -304,6 +301,7 @@ public class PageMapperMethod {
         private final boolean returnsMap;
         private final boolean returnsVoid;
         private final boolean returnsCursor;
+        private final boolean returnsOptional;
         private final Class<?> returnType;
         private final String mapKey;
         private final Integer resultHandlerIndex;
@@ -322,6 +320,7 @@ public class PageMapperMethod {
             this.returnsVoid = void.class.equals(this.returnType);
             this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
             this.returnsCursor = Cursor.class.equals(this.returnType);
+            this.returnsOptional = Optional.class.equals(this.returnType);
             this.mapKey = getMapKey(method);
             this.returnsMap = this.mapKey != null;
             this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
@@ -373,6 +372,16 @@ public class PageMapperMethod {
             return returnsCursor;
         }
 
+        /**
+         * return whether return type is {@code java.util.Optional}
+         *
+         * @return return {@code true}, if return type is {@code java.util.Optional}
+         * @since 3.5.0
+         */
+        public boolean returnsOptional() {
+            return returnsOptional;
+        }
+
         private Integer getUniqueParamIndex(Method method, Class<?> paramType) {
             Integer index = null;
             final Class<?>[] argTypes = method.getParameterTypes();

+ 4 - 11
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/override/PageMapperProxy.java

@@ -15,6 +15,9 @@
  */
 package com.baomidou.mybatisplus.core.override;
 
+import org.apache.ibatis.reflection.ExceptionUtil;
+import org.apache.ibatis.session.SqlSession;
+
 import java.io.Serializable;
 import java.lang.invoke.MethodHandles;
 import java.lang.reflect.Constructor;
@@ -23,10 +26,6 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.Map;
 
-import org.apache.ibatis.lang.UsesJava7;
-import org.apache.ibatis.reflection.ExceptionUtil;
-import org.apache.ibatis.session.SqlSession;
-
 /**
  * <p>
  * 替换掉引用<br/>
@@ -65,15 +64,9 @@ public class PageMapperProxy<T> implements InvocationHandler, Serializable {
     }
 
     private PageMapperMethod cachedMapperMethod(Method method) {
-        PageMapperMethod mapperMethod = methodCache.get(method);
-        if (mapperMethod == null) {
-            mapperMethod = new PageMapperMethod(mapperInterface, method, sqlSession.getConfiguration());
-            methodCache.put(method, mapperMethod);
-        }
-        return mapperMethod;
+        return methodCache.computeIfAbsent(method, k -> new PageMapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
     }
 
-    @UsesJava7
     private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
         throws Throwable {
         final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class

+ 2 - 2
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/override/PageMapperProxyFactory.java

@@ -15,13 +15,13 @@
  */
 package com.baomidou.mybatisplus.core.override;
 
+import org.apache.ibatis.session.SqlSession;
+
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
-import org.apache.ibatis.session.SqlSession;
-
 /**
  * <p>
  * 替换掉引用<br/>

+ 0 - 7
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/PaginationInterceptor.java

@@ -181,13 +181,6 @@ public class PaginationInterceptor extends AbstractSqlParserHandler implements I
         model.consumers(mappings, configuration, additionalParameters);
         metaObject.setValue("delegate.boundSql.sql", model.getDialectSql());
         metaObject.setValue("delegate.boundSql.parameterMappings", mappings);
-
-        /*
-         * <p> 禁用内存分页 </p>
-         * <p> 内存分页会查询所有结果出来处理(这个很吓人的),如果结果变化频繁这个数据还会不准。</p>
-         */
-        metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
-        metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
         return invocation.proceed();
     }