Caratacus 8 роки тому
батько
коміт
9e252c36e6
72 змінених файлів з 1228 додано та 1216 видалено
  1. 1 1
      src/main/java/com/baomidou/mybatisplus/MybatisConfiguration.java
  2. 6 5
      src/main/java/com/baomidou/mybatisplus/MybatisDefaultParameterHandler.java
  3. 52 9
      src/main/java/com/baomidou/mybatisplus/MybatisMapperAnnotationBuilder.java
  4. 13 8
      src/main/java/com/baomidou/mybatisplus/MybatisXMLConfigBuilder.java
  5. 3 3
      src/main/java/com/baomidou/mybatisplus/annotations/TableField.java
  6. 12 12
      src/main/java/com/baomidou/mybatisplus/annotations/TableLogic.java
  7. 4 4
      src/main/java/com/baomidou/mybatisplus/entity/TableFieldInfo.java
  8. 2 3
      src/main/java/com/baomidou/mybatisplus/entity/TableInfo.java
  9. 1 2
      src/main/java/com/baomidou/mybatisplus/enums/DBType.java
  10. 7 4
      src/main/java/com/baomidou/mybatisplus/enums/IdType.java
  11. 1 2
      src/main/java/com/baomidou/mybatisplus/enums/Optimize.java
  12. 6 2
      src/main/java/com/baomidou/mybatisplus/enums/SqlLike.java
  13. 6 6
      src/main/java/com/baomidou/mybatisplus/enums/SqlMethod.java
  14. 1 2
      src/main/java/com/baomidou/mybatisplus/generator/config/ITypeConvert.java
  15. 18 8
      src/main/java/com/baomidou/mybatisplus/generator/config/builder/ConfigBuilder.java
  16. 5 5
      src/main/java/com/baomidou/mybatisplus/mapper/AutoSqlInjector.java
  17. 22 44
      src/main/java/com/baomidou/mybatisplus/mapper/BaseMapper.java
  18. 1 1
      src/main/java/com/baomidou/mybatisplus/mapper/EntityWrapper.java
  19. 250 253
      src/main/java/com/baomidou/mybatisplus/mapper/LogicSqlInjector.java
  20. 16 15
      src/main/java/com/baomidou/mybatisplus/mapper/MetaObjectHandler.java
  21. 41 40
      src/main/java/com/baomidou/mybatisplus/mapper/Wrapper.java
  22. 50 49
      src/main/java/com/baomidou/mybatisplus/plugins/OptimisticLockerInterceptor.java
  23. 5 4
      src/main/java/com/baomidou/mybatisplus/plugins/PerformanceInterceptor.java
  24. 7 14
      src/main/java/com/baomidou/mybatisplus/plugins/pagination/DialectFactory.java
  25. 3 6
      src/main/java/com/baomidou/mybatisplus/plugins/pagination/IDialect.java
  26. 2 5
      src/main/java/com/baomidou/mybatisplus/plugins/pagination/Pagination.java
  27. 14 0
      src/main/java/com/baomidou/mybatisplus/plugins/pagination/dialects/DB2Dialect.java
  28. 34 69
      src/main/java/com/baomidou/mybatisplus/service/IService.java
  29. 1 1
      src/main/java/com/baomidou/mybatisplus/service/impl/ServiceImpl.java
  30. 3 1
      src/main/java/com/baomidou/mybatisplus/spring/MybatisMapperRefresh.java
  31. 18 16
      src/main/java/com/baomidou/mybatisplus/spring/MybatisSqlSessionFactoryBean.java
  32. 1 2
      src/main/java/com/baomidou/mybatisplus/toolkit/JdbcUtils.java
  33. 1 2
      src/main/java/com/baomidou/mybatisplus/toolkit/JsqlParserUtils.java
  34. 1 2
      src/main/java/com/baomidou/mybatisplus/toolkit/PackageHelper.java
  35. 5 6
      src/main/java/com/baomidou/mybatisplus/toolkit/Sequence.java
  36. 8 10
      src/main/java/com/baomidou/mybatisplus/toolkit/SqlReservedWords.java
  37. 7 14
      src/main/java/com/baomidou/mybatisplus/toolkit/SqlUtils.java
  38. 1 1
      src/test/java/com/baomidou/mybatisplus/test/EntityWrapperTest.java
  39. 2 2
      src/test/java/com/baomidou/mybatisplus/test/GlobalConfigurationTest.java
  40. 55 55
      src/test/java/com/baomidou/mybatisplus/test/IdWorkerTest.java
  41. 60 59
      src/test/java/com/baomidou/mybatisplus/test/SnowFlake.java
  42. 6 1
      src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java
  43. 2 2
      src/test/java/com/baomidou/mybatisplus/test/h2/H2MetaObjectHandlerTest.java
  44. 7 6
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserAddrJoinTest.java
  45. 1 1
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserAutoincrementTest.java
  46. 11 11
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserDateVersionTest.java
  47. 19 18
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserNoOptLockTest.java
  48. 7 7
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserNoVersionTest.java
  49. 2 2
      src/test/java/com/baomidou/mybatisplus/test/h2/H2UserTest.java
  50. 2 2
      src/test/java/com/baomidou/mybatisplus/test/h2/entity/mapper/H2UserMapper.java
  51. 5 5
      src/test/java/com/baomidou/mybatisplus/test/mysql/LogicDeleteTest.java
  52. 2 2
      src/test/java/com/baomidou/mybatisplus/test/mysql/MyMetaObjectHandler.java
  53. 1 1
      src/test/java/com/baomidou/mybatisplus/test/mysql/NoXMLTest.java
  54. 1 1
      src/test/java/com/baomidou/mybatisplus/test/mysql/SqlRunnerTest.java
  55. 1 1
      src/test/java/com/baomidou/mybatisplus/test/mysql/TransactionalTest.java
  56. 10 9
      src/test/java/com/baomidou/mybatisplus/test/mysql/UserMapperTest.java
  57. 12 4
      src/test/java/com/baomidou/mybatisplus/test/mysql/entity/Role.java
  58. 3 1
      src/test/java/com/baomidou/mybatisplus/test/mysql/entity/Test.java
  59. 1 2
      src/test/java/com/baomidou/mybatisplus/test/mysql/mapper/UserMapper.java
  60. 4 4
      src/test/java/com/baomidou/mybatisplus/test/oracle/OracleUserTest.java
  61. 1 3
      src/test/java/com/baomidou/mybatisplus/test/oracle/TestSequserMapperTest.java
  62. 1 3
      src/test/java/com/baomidou/mybatisplus/test/oracle/TestUserMapperTest.java
  63. 9 10
      src/test/java/com/baomidou/mybatisplus/test/oracle/config/OracleDBConfig.java
  64. 9 9
      src/test/java/com/baomidou/mybatisplus/test/oracle/entity/BaseTestEntity.java
  65. 51 52
      src/test/java/com/baomidou/mybatisplus/test/oracle/entity/TestSequser.java
  66. 1 1
      src/test/java/com/baomidou/mybatisplus/test/oracle/service/impl/OracleUserSeqServiceImpl.java
  67. 162 162
      src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/OptimisticLockerInterceptorTest.java
  68. 1 0
      src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/IntVersionFather.java
  69. 23 23
      src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/IntVersionUser.java
  70. 33 33
      src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/LogicVersionUser.java
  71. 66 65
      src/test/java/com/baomidou/mybatisplus/test/plugins/paginationInterceptor/PaginationInterceptorTest.java
  72. 28 28
      src/test/java/com/baomidou/mybatisplus/test/plugins/paginationInterceptor/entity/PageUser.java

+ 1 - 1
src/main/java/com/baomidou/mybatisplus/MybatisConfiguration.java

@@ -71,7 +71,7 @@ public class MybatisConfiguration extends Configuration {
             this.mappedStatements.remove(ms.getId());
         } else {
             if (this.mappedStatements.containsKey(ms.getId())) {
-				/*
+                /*
 				 * 说明已加载了xml中的节点; 忽略mapper中的SqlProvider数据
 				 */
                 logger.error("mapper[" + ms.getId() + "] is ignored, because it's exists, maybe from xml file");

+ 6 - 5
src/main/java/com/baomidou/mybatisplus/MybatisDefaultParameterHandler.java

@@ -66,6 +66,7 @@ public class MybatisDefaultParameterHandler extends DefaultParameterHandler {
     private final Object parameterObject;
     private BoundSql boundSql;
     private Configuration configuration;
+
     public MybatisDefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
         super(mappedStatement, processBatch(mappedStatement, parameterObject), boundSql);
         this.mappedStatement = mappedStatement;
@@ -130,14 +131,14 @@ public class MybatisDefaultParameterHandler extends DefaultParameterHandler {
                 return objList;
             } else {
                 TableInfo tableInfo;
-                if(parameterObject instanceof java.util.Map){
-                    Object et = ((java.util.Map)parameterObject).get("et");
-                    if(et!=null){
+                if (parameterObject instanceof java.util.Map) {
+                    Object et = ((java.util.Map) parameterObject).get("et");
+                    if (et != null) {
                         tableInfo = TableInfoHelper.getTableInfo(et.getClass());
-                    }else{
+                    } else {
                         tableInfo = null;
                     }
-                }else{
+                } else {
                     tableInfo = TableInfoHelper.getTableInfo(parameterObject.getClass());
                 }
                 return populateKeys(metaObjectHandler, tableInfo, ms, parameterObject);

+ 52 - 9
src/main/java/com/baomidou/mybatisplus/MybatisMapperAnnotationBuilder.java

@@ -15,11 +15,49 @@
  */
 package com.baomidou.mybatisplus;
 
-import com.baomidou.mybatisplus.entity.GlobalConfiguration;
-import com.baomidou.mybatisplus.mapper.BaseMapper;
-import org.apache.ibatis.annotations.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.apache.ibatis.annotations.Arg;
+import org.apache.ibatis.annotations.CacheNamespace;
+import org.apache.ibatis.annotations.CacheNamespaceRef;
+import org.apache.ibatis.annotations.Case;
+import org.apache.ibatis.annotations.ConstructorArgs;
+import org.apache.ibatis.annotations.Delete;
+import org.apache.ibatis.annotations.DeleteProvider;
+import org.apache.ibatis.annotations.Insert;
+import org.apache.ibatis.annotations.InsertProvider;
+import org.apache.ibatis.annotations.Lang;
+import org.apache.ibatis.annotations.MapKey;
+import org.apache.ibatis.annotations.Options;
 import org.apache.ibatis.annotations.Options.FlushCachePolicy;
+import org.apache.ibatis.annotations.Property;
+import org.apache.ibatis.annotations.Result;
 import org.apache.ibatis.annotations.ResultMap;
+import org.apache.ibatis.annotations.ResultType;
+import org.apache.ibatis.annotations.Results;
+import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.SelectKey;
+import org.apache.ibatis.annotations.SelectProvider;
+import org.apache.ibatis.annotations.TypeDiscriminator;
+import org.apache.ibatis.annotations.Update;
+import org.apache.ibatis.annotations.UpdateProvider;
 import org.apache.ibatis.binding.BindingException;
 import org.apache.ibatis.binding.MapperMethod.ParamMap;
 import org.apache.ibatis.builder.BuilderException;
@@ -35,7 +73,15 @@ import org.apache.ibatis.executor.keygen.KeyGenerator;
 import org.apache.ibatis.executor.keygen.NoKeyGenerator;
 import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
 import org.apache.ibatis.io.Resources;
-import org.apache.ibatis.mapping.*;
+import org.apache.ibatis.mapping.Discriminator;
+import org.apache.ibatis.mapping.FetchType;
+import org.apache.ibatis.mapping.MappedStatement;
+import org.apache.ibatis.mapping.ResultFlag;
+import org.apache.ibatis.mapping.ResultMapping;
+import org.apache.ibatis.mapping.ResultSetType;
+import org.apache.ibatis.mapping.SqlCommandType;
+import org.apache.ibatis.mapping.SqlSource;
+import org.apache.ibatis.mapping.StatementType;
 import org.apache.ibatis.parsing.PropertyParser;
 import org.apache.ibatis.reflection.TypeParameterResolver;
 import org.apache.ibatis.scripting.LanguageDriver;
@@ -46,11 +92,8 @@ import org.apache.ibatis.type.JdbcType;
 import org.apache.ibatis.type.TypeHandler;
 import org.apache.ibatis.type.UnknownTypeHandler;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.*;
-import java.util.*;
+import com.baomidou.mybatisplus.entity.GlobalConfiguration;
+import com.baomidou.mybatisplus.mapper.BaseMapper;
 
 /**
  * <p>

+ 13 - 8
src/main/java/com/baomidou/mybatisplus/MybatisXMLConfigBuilder.java

@@ -15,6 +15,14 @@
  */
 package com.baomidou.mybatisplus;
 
+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;
@@ -36,17 +44,14 @@ 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.*;
+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.transaction.TransactionFactory;
 import org.apache.ibatis.type.JdbcType;
 
-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>
  * Copy from XMLConfigBuilder in Mybatis and replace default Configuration class

+ 3 - 3
src/main/java/com/baomidou/mybatisplus/annotations/TableField.java

@@ -15,14 +15,14 @@
  */
 package com.baomidou.mybatisplus.annotations;
 
-import com.baomidou.mybatisplus.enums.FieldIgnore;
-import com.baomidou.mybatisplus.enums.FieldStrategy;
-
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
+import com.baomidou.mybatisplus.enums.FieldIgnore;
+import com.baomidou.mybatisplus.enums.FieldStrategy;
+
 /**
  * <p>
  * 表字段标识

+ 12 - 12
src/main/java/com/baomidou/mybatisplus/annotations/TableLogic.java

@@ -32,18 +32,18 @@ import java.lang.annotation.Target;
 @Target(ElementType.FIELD)
 public @interface TableLogic {
 
-	/**
-	 * <p>
-	 * 默认逻辑未删除值(该值可无、会自动获取全局配置)
-	 * </p>
-	 */
-	String value() default "";
+    /**
+     * <p>
+     * 默认逻辑未删除值(该值可无、会自动获取全局配置)
+     * </p>
+     */
+    String value() default "";
 
-	/**
-	 * <p>
-	 * 默认逻辑删除值(该值可无、会自动获取全局配置)
-	 * </p>
-	 */
-	String delval() default "";
+    /**
+     * <p>
+     * 默认逻辑删除值(该值可无、会自动获取全局配置)
+     * </p>
+     */
+    String delval() default "";
 
 }

+ 4 - 4
src/main/java/com/baomidou/mybatisplus/entity/TableFieldInfo.java

@@ -15,6 +15,8 @@
  */
 package com.baomidou.mybatisplus.entity;
 
+import java.lang.reflect.Field;
+
 import com.baomidou.mybatisplus.annotations.TableField;
 import com.baomidou.mybatisplus.annotations.TableLogic;
 import com.baomidou.mybatisplus.enums.FieldIgnore;
@@ -22,8 +24,6 @@ import com.baomidou.mybatisplus.enums.FieldStrategy;
 import com.baomidou.mybatisplus.toolkit.SqlReservedWords;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 
-import java.lang.reflect.Field;
-
 /**
  * <p>
  * 数据库表字段反射信息
@@ -117,10 +117,10 @@ public class TableFieldInfo {
             this.fieldStrategy = globalConfig.getFieldStrategy();
         }
         tableInfo.setLogicDelete(this.initLogicDelete(globalConfig, field));
-		/*
+        /*
 		 * 保存当前字段的插入忽略,更新忽略值
 		 */
-		this.fieldIgnore = tableField.ignore();
+        this.fieldIgnore = tableField.ignore();
     }
 
     public TableFieldInfo(GlobalConfiguration globalConfig, TableInfo tableInfo, Field field) {

+ 2 - 3
src/main/java/com/baomidou/mybatisplus/entity/TableInfo.java

@@ -94,8 +94,7 @@ public class TableInfo {
      * 获得注入的 SQL Statement
      * </p>
      *
-     * @param sqlMethod
-     *            MybatisPlus 支持 SQL 方法
+     * @param sqlMethod MybatisPlus 支持 SQL 方法
      * @return
      */
     public String getSqlStatement(String sqlMethod) {
@@ -172,7 +171,7 @@ public class TableInfo {
          * 启动逻辑删除注入、判断该表是否启动
          */
         if (null != globalConfig.getLogicDeleteValue()) {
-            for (TableFieldInfo tfi: fieldList) {
+            for (TableFieldInfo tfi : fieldList) {
                 if (tfi.isLogicDelete()) {
                     this.setLogicDelete(true);
                     break;

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/enums/DBType.java

@@ -82,8 +82,7 @@ public enum DBType {
      * 获取数据库类型(默认 MySql)
      * </p>
      *
-     * @param dbType
-     *            数据库类型字符串
+     * @param dbType 数据库类型字符串
      * @return
      */
     public static DBType getDBType(String dbType) {

+ 7 - 4
src/main/java/com/baomidou/mybatisplus/enums/IdType.java

@@ -29,10 +29,14 @@ public enum IdType {
     /* 以下2种类型、只有当插入对象ID 为空,才自动填充。 */
     ID_WORKER(2, "全局唯一ID"), UUID(3, "全局唯一ID"), NONE(4, "该类型为未设置主键类型");
 
-    /** 主键 */
+    /**
+     * 主键
+     */
     private final int key;
 
-    /** 描述 */
+    /**
+     * 描述
+     */
     private final String desc;
 
     IdType(final int key, final String desc) {
@@ -45,8 +49,7 @@ public enum IdType {
      * 主键策略 (默认 ID_WORKER)
      * </p>
      *
-     * @param idType
-     *            ID 策略类型
+     * @param idType ID 策略类型
      * @return
      */
     public static IdType getIdType(int idType) {

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/enums/Optimize.java

@@ -51,8 +51,7 @@ public enum Optimize {
      * 获取优化类型.如果没有找到默认DEFAULT
      * </p>
      *
-     * @param optimizeType
-     *            优化方式
+     * @param optimizeType 优化方式
      * @return
      */
     public static Optimize getOptimizeType(String optimizeType) {

+ 6 - 2
src/main/java/com/baomidou/mybatisplus/enums/SqlLike.java

@@ -41,10 +41,14 @@ public enum SqlLike {
      */
     DEFAULT("default", "两边%");
 
-    /** 主键 */
+    /**
+     * 主键
+     */
     private final String type;
 
-    /** 描述 */
+    /**
+     * 描述
+     */
     private final String desc;
 
     SqlLike(final String type, final String desc) {

+ 6 - 6
src/main/java/com/baomidou/mybatisplus/enums/SqlMethod.java

@@ -58,8 +58,8 @@ public enum SqlMethod {
      */
     LOGIC_UPDATE_BY_ID("updateById", "根据ID 修改数据", "<script>UPDATE %s %s WHERE %s=#{%s} %s</script>"),
     LOGIC_UPDATE_ALL_COLUMN_BY_ID("updateAllColumnById", "根据ID 选择修改数据", "<script>UPDATE %s %s WHERE %s=#{%s} %s</script>"),
-    
-    
+
+
     /**
      * 查询
      */
@@ -74,12 +74,12 @@ public enum SqlMethod {
     SELECT_MAPS_PAGE("selectMapsPage", "查询满足条件所有数据(并翻页)", "<script>SELECT %s FROM %s %s</script>"),
     SELECT_OBJS("selectObjs", "查询满足条件所有数据", "<script>SELECT %s FROM %s %s</script>"),
 
-	/**
+    /**
      * 逻辑删除 -> 查询
      */
-	LOGIC_SELECT_BY_ID("selectById", "根据ID 查询一条数据", "SELECT %s FROM %s WHERE %s=#{%s} %s"),
-	LOGIC_SELECT_BATCH_BY_IDS("selectBatchIds", "根据ID集合,批量查询数据", "<script>SELECT %s FROM %s WHERE %s IN (%s) %s</script>");
-	
+    LOGIC_SELECT_BY_ID("selectById", "根据ID 查询一条数据", "SELECT %s FROM %s WHERE %s=#{%s} %s"),
+    LOGIC_SELECT_BATCH_BY_IDS("selectBatchIds", "根据ID集合,批量查询数据", "<script>SELECT %s FROM %s WHERE %s IN (%s) %s</script>");
+
     private final String method;
     private final String desc;
     private final String sql;

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/generator/config/ITypeConvert.java

@@ -32,8 +32,7 @@ public interface ITypeConvert {
      * 执行类型转换
      * </p>
      *
-     * @param fieldType
-     *            字段类型
+     * @param fieldType 字段类型
      * @return
      */
     DbColumnType processTypeConvert(String fieldType);

+ 18 - 8
src/main/java/com/baomidou/mybatisplus/generator/config/builder/ConfigBuilder.java

@@ -15,7 +15,24 @@
  */
 package com.baomidou.mybatisplus.generator.config.builder;
 
-import com.baomidou.mybatisplus.generator.config.*;
+import java.io.File;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.baomidou.mybatisplus.generator.config.ConstVal;
+import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.PackageConfig;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.TemplateConfig;
 import com.baomidou.mybatisplus.generator.config.po.TableField;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
@@ -23,13 +40,6 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 import com.baomidou.mybatisplus.generator.config.rules.QuerySQL;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 
-import java.io.File;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.*;
-
 /**
  * 配置汇总 传递给文件生成工具
  *

+ 5 - 5
src/main/java/com/baomidou/mybatisplus/mapper/AutoSqlInjector.java

@@ -141,7 +141,7 @@ public class AutoSqlInjector implements ISqlInjector {
         /* 删除 */
         this.injectDeleteSql(mapperClass, modelClass, table);
         this.injectDeleteByMapSql(mapperClass, table);
-		/* 修改 */
+        /* 修改 */
         this.injectUpdateSql(mapperClass, modelClass, table);
 		/* 查询 */
         this.injectSelectByMapSql(mapperClass, modelClass, table);
@@ -336,12 +336,12 @@ public class AutoSqlInjector implements ISqlInjector {
     protected void injectUpdateByIdSql(boolean selective, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
         SqlMethod sqlMethod = selective ? SqlMethod.UPDATE_BY_ID : SqlMethod.UPDATE_ALL_COLUMN_BY_ID;
         String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlSet(selective, table, "et."), table.getKeyColumn(),
-                "et."+table.getKeyProperty(),
-                "<if test=\"et instanceof java.util.Map\">"+
+                "et." + table.getKeyProperty(),
+                "<if test=\"et instanceof java.util.Map\">" +
                         "<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">"
-                        +"and ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}"
+                        + "and ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}"
+                        + "</if>"
                         + "</if>"
-                +"</if>"
         );
         SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
         this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);

+ 22 - 44
src/main/java/com/baomidou/mybatisplus/mapper/BaseMapper.java

@@ -40,8 +40,7 @@ public interface BaseMapper<T> {
      * 插入一条记录
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return int
      */
     Integer insert(T entity);
@@ -51,8 +50,7 @@ public interface BaseMapper<T> {
      * 插入一条记录
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return int
      */
     Integer insertAllColumn(T entity);
@@ -62,8 +60,7 @@ public interface BaseMapper<T> {
      * 根据 ID 删除
      * </p>
      *
-     * @param id
-     *            主键ID
+     * @param id 主键ID
      * @return int
      */
     Integer deleteById(Serializable id);
@@ -73,8 +70,7 @@ public interface BaseMapper<T> {
      * 根据 columnMap 条件,删除记录
      * </p>
      *
-     * @param columnMap
-     *            表字段 map 对象
+     * @param columnMap 表字段 map 对象
      * @return int
      */
     Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);
@@ -84,8 +80,7 @@ public interface BaseMapper<T> {
      * 根据 entity 条件,删除记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return int
      */
     Integer delete(@Param("ew") Wrapper<T> wrapper);
@@ -95,8 +90,7 @@ public interface BaseMapper<T> {
      * 删除(根据ID 批量删除)
      * </p>
      *
-     * @param idList
-     *            主键ID列表
+     * @param idList 主键ID列表
      * @return int
      */
     Integer deleteBatchIds(List<? extends Serializable> idList);
@@ -106,8 +100,7 @@ public interface BaseMapper<T> {
      * 根据 ID 修改
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return int
      */
     Integer updateById(@Param("et") T entity);
@@ -117,8 +110,7 @@ public interface BaseMapper<T> {
      * 根据 ID 修改
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return int
      */
     Integer updateAllColumnById(@Param("et") T entity);
@@ -128,10 +120,8 @@ public interface BaseMapper<T> {
      * 根据 whereEntity 条件,更新记录
      * </p>
      *
-     * @param entity
-     *            实体对象
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param entity  实体对象
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return
      */
     Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);
@@ -141,8 +131,7 @@ public interface BaseMapper<T> {
      * 根据 ID 查询
      * </p>
      *
-     * @param id
-     *            主键ID
+     * @param id 主键ID
      * @return T
      */
     T selectById(Serializable id);
@@ -152,8 +141,7 @@ public interface BaseMapper<T> {
      * 查询(根据ID 批量查询)
      * </p>
      *
-     * @param idList
-     *            主键ID列表
+     * @param idList 主键ID列表
      * @return List<T>
      */
     List<T> selectBatchIds(List<? extends Serializable> idList);
@@ -163,8 +151,7 @@ public interface BaseMapper<T> {
      * 查询(根据 columnMap 条件)
      * </p>
      *
-     * @param columnMap
-     *            表字段 map 对象
+     * @param columnMap 表字段 map 对象
      * @return List<T>
      */
     List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
@@ -174,8 +161,7 @@ public interface BaseMapper<T> {
      * 根据 entity 条件,查询一条记录
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return T
      */
     T selectOne(@Param("ew") T entity);
@@ -185,8 +171,7 @@ public interface BaseMapper<T> {
      * 根据 Wrapper 条件,查询总记录数
      * </p>
      *
-     * @param wrapper
-     *            实体对象
+     * @param wrapper 实体对象
      * @return int
      */
     Integer selectCount(@Param("ew") Wrapper<T> wrapper);
@@ -196,8 +181,7 @@ public interface BaseMapper<T> {
      * 根据 entity 条件,查询全部记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return List<T>
      */
     List<T> selectList(@Param("ew") Wrapper<T> wrapper);
@@ -207,8 +191,7 @@ public interface BaseMapper<T> {
      * 根据 Wrapper 条件,查询全部记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return List<T>
      */
     List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper);
@@ -218,8 +201,7 @@ public interface BaseMapper<T> {
      * 根据 Wrapper 条件,查询全部记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return List<Object>
      */
     List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper);
@@ -229,10 +211,8 @@ public interface BaseMapper<T> {
      * 根据 entity 条件,查询全部记录(并翻页)
      * </p>
      *
-     * @param rowBounds
-     *            分页查询条件(可以为 RowBounds.DEFAULT)
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT)
+     * @param wrapper   实体对象封装操作类(可以为 null)
      * @return List<T>
      */
     List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
@@ -242,10 +222,8 @@ public interface BaseMapper<T> {
      * 根据 Wrapper 条件,查询全部记录(并翻页)
      * </p>
      *
-     * @param rowBounds
-     *            分页查询条件(可以为 RowBounds.DEFAULT)
-     * @param wrapper
-     *            实体对象封装操作类
+     * @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT)
+     * @param wrapper   实体对象封装操作类
      * @return List<Map<String, Object>>
      */
     List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

+ 1 - 1
src/main/java/com/baomidou/mybatisplus/mapper/EntityWrapper.java

@@ -59,7 +59,7 @@ public class EntityWrapper<T> extends Wrapper<T> {
      */
     @Override
     public String getSqlSegment() {
-		/*
+        /*
 		 * 无条件
 		 */
         String sqlWhere = sql.toString();

+ 250 - 253
src/main/java/com/baomidou/mybatisplus/mapper/LogicSqlInjector.java

@@ -38,269 +38,266 @@ import com.baomidou.mybatisplus.toolkit.StringUtils;
  */
 public class LogicSqlInjector extends AutoSqlInjector {
 
-	/**
-	 * 根据 ID 删除
-	 */
-	@Override
-	protected void injectDeleteByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
-		if (table.isLogicDelete()) {
-			// 逻辑删除注入
-			SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_ID;
-			SqlSource sqlSource;
-			String idStr = table.getKeyColumn();
-			if (batch) {
-				sqlMethod = SqlMethod.LOGIC_DELETE_BATCH_BY_IDS;
-				StringBuilder ids = new StringBuilder();
-				ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
-				ids.append("#{item}");
-				ids.append("\n</foreach>");
-				idStr = ids.toString();
-			}
-			String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
-					table.getKeyColumn(), idStr);
-			sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
-			this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
-		} else {
-			// 正常删除
-			super.injectDeleteByIdSql(batch, mapperClass, modelClass, table);
-		}
-	}
+    /**
+     * 根据 ID 删除
+     */
+    @Override
+    protected void injectDeleteByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
+        if (table.isLogicDelete()) {
+            // 逻辑删除注入
+            SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_ID;
+            SqlSource sqlSource;
+            String idStr = table.getKeyColumn();
+            if (batch) {
+                sqlMethod = SqlMethod.LOGIC_DELETE_BATCH_BY_IDS;
+                StringBuilder ids = new StringBuilder();
+                ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
+                ids.append("#{item}");
+                ids.append("\n</foreach>");
+                idStr = ids.toString();
+            }
+            String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
+                    table.getKeyColumn(), idStr);
+            sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
+            this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
+        } else {
+            // 正常删除
+            super.injectDeleteByIdSql(batch, mapperClass, modelClass, table);
+        }
+    }
 
-	/**
-	 * 根据 SQL 删除
-	 */
-	@Override
-	protected void injectDeleteSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
-		if (table.isLogicDelete()) {
-			// 逻辑删除注入
-			SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE;
-			String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
-					sqlWhereEntityWrapper(table));
-			SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
-			this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
-		} else {
-			// 正常删除
-			super.injectDeleteSql(mapperClass, modelClass, table);
-		}
-	}
+    /**
+     * 根据 SQL 删除
+     */
+    @Override
+    protected void injectDeleteSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
+        if (table.isLogicDelete()) {
+            // 逻辑删除注入
+            SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE;
+            String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
+                    sqlWhereEntityWrapper(table));
+            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
+            this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
+        } else {
+            // 正常删除
+            super.injectDeleteSql(mapperClass, modelClass, table);
+        }
+    }
 
-	/**
-	 * 根据 MAP 删除
-	 */
-	@Override
-	protected void injectDeleteByMapSql(Class<?> mapperClass, TableInfo table) {
-		if (table.isLogicDelete()) {
-			// 逻辑删除注入
-			SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_MAP;
-			String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
-					sqlWhereByMap(table));
-			SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);
-			this.addUpdateMappedStatement(mapperClass, Map.class, sqlMethod.getMethod(), sqlSource);
-		} else {
-			// 正常删除
-			super.injectDeleteByMapSql(mapperClass, table);
-		}
-	}
+    /**
+     * 根据 MAP 删除
+     */
+    @Override
+    protected void injectDeleteByMapSql(Class<?> mapperClass, TableInfo table) {
+        if (table.isLogicDelete()) {
+            // 逻辑删除注入
+            SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_MAP;
+            String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlLogicSet(table),
+                    sqlWhereByMap(table));
+            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);
+            this.addUpdateMappedStatement(mapperClass, Map.class, sqlMethod.getMethod(), sqlSource);
+        } else {
+            // 正常删除
+            super.injectDeleteByMapSql(mapperClass, table);
+        }
+    }
 
-	/**
-	 * <p>
-	 * 注入查询 SQL 语句
-	 * </p>
-	 *
-	 * @param batch
-	 *            是否为批量插入
-	 * @param mapperClass
-	 * @param modelClass
-	 * @param table
-	 */
-	protected void injectSelectByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
-		if (table.isLogicDelete()) {
-			SqlMethod sqlMethod = SqlMethod.LOGIC_SELECT_BY_ID;
-			SqlSource sqlSource;
-			if (batch) {
-				sqlMethod = SqlMethod.LOGIC_SELECT_BATCH_BY_IDS;
-				StringBuilder ids = new StringBuilder();
-				ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
-				ids.append("#{item}");
-				ids.append("\n</foreach>");
-				sqlSource = languageDriver.createSqlSource(configuration, String.format(sqlMethod.getSql(), sqlSelectColumns(table, false),
-								table.getTableName(), table.getKeyColumn(), ids.toString(), getLogicDeleteSql(table)), modelClass);
-			} else {
-				sqlSource = new RawSqlSource(configuration, String.format(sqlMethod.getSql(), sqlSelectColumns(table, false), table.getTableName(),
-								table.getKeyColumn(), table.getKeyProperty(), getLogicDeleteSql(table)), Object.class);
-			}
-			this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
-		} else {
-			// 正常查询
-			super.injectSelectByIdSql(batch, mapperClass, modelClass, table);
-		}
-	}
+    /**
+     * <p>
+     * 注入查询 SQL 语句
+     * </p>
+     *
+     * @param batch       是否为批量插入
+     * @param mapperClass
+     * @param modelClass
+     * @param table
+     */
+    protected void injectSelectByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
+        if (table.isLogicDelete()) {
+            SqlMethod sqlMethod = SqlMethod.LOGIC_SELECT_BY_ID;
+            SqlSource sqlSource;
+            if (batch) {
+                sqlMethod = SqlMethod.LOGIC_SELECT_BATCH_BY_IDS;
+                StringBuilder ids = new StringBuilder();
+                ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
+                ids.append("#{item}");
+                ids.append("\n</foreach>");
+                sqlSource = languageDriver.createSqlSource(configuration, String.format(sqlMethod.getSql(), sqlSelectColumns(table, false),
+                        table.getTableName(), table.getKeyColumn(), ids.toString(), getLogicDeleteSql(table)), modelClass);
+            } else {
+                sqlSource = new RawSqlSource(configuration, String.format(sqlMethod.getSql(), sqlSelectColumns(table, false), table.getTableName(),
+                        table.getKeyColumn(), table.getKeyProperty(), getLogicDeleteSql(table)), Object.class);
+            }
+            this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
+        } else {
+            // 正常查询
+            super.injectSelectByIdSql(batch, mapperClass, modelClass, table);
+        }
+    }
 
-	/**
-	 * <p>
-	 * 注入更新 SQL 语句
-	 * </p>
-	 *
-	 * @param mapperClass
-	 * @param modelClass
-	 * @param table
-	 */
-	protected void injectUpdateByIdSql(boolean selective, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
-		if (table.isLogicDelete()) {
-			SqlMethod sqlMethod = selective ? SqlMethod.LOGIC_UPDATE_BY_ID : SqlMethod.LOGIC_UPDATE_ALL_COLUMN_BY_ID;
-			String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlSet(selective, table, null),
-					table.getKeyColumn(), table.getKeyProperty(),
-					"<if test=\"et instanceof java.util.Map\">"+
-						"<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">"
-							+"and ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}"
-						+ "</if>"
-					+"</if>"+
-					getLogicDeleteSql(table)
-			);
-			SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
-			this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
-		} else {
-			super.injectUpdateByIdSql(selective, mapperClass, modelClass, table);
-		}
-	}
+    /**
+     * <p>
+     * 注入更新 SQL 语句
+     * </p>
+     *
+     * @param mapperClass
+     * @param modelClass
+     * @param table
+     */
+    protected void injectUpdateByIdSql(boolean selective, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
+        if (table.isLogicDelete()) {
+            SqlMethod sqlMethod = selective ? SqlMethod.LOGIC_UPDATE_BY_ID : SqlMethod.LOGIC_UPDATE_ALL_COLUMN_BY_ID;
+            String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlSet(selective, table, null),
+                    table.getKeyColumn(), table.getKeyProperty(),
+                    "<if test=\"et instanceof java.util.Map\">" +
+                            "<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">"
+                            + "and ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}"
+                            + "</if>"
+                            + "</if>" +
+                            getLogicDeleteSql(table)
+            );
+            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
+            this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
+        } else {
+            super.injectUpdateByIdSql(selective, mapperClass, modelClass, table);
+        }
+    }
 
-	/**
-	 * <p>
-	 * SQL 更新 set 语句
-	 * </p>
-	 *
-	 * @param table
-	 *            表信息
-	 * @return sql and 片段
-	 */
-	public String getLogicDeleteSql(TableInfo table) {
-		StringBuilder sql = new StringBuilder();
-		List<TableFieldInfo> fieldList = table.getFieldList();
-		for (TableFieldInfo fieldInfo : fieldList) {
-			if (fieldInfo.isLogicDelete()) {
-				sql.append(" AND ").append(fieldInfo.getColumn());
-				if ("java.lang.String".equals(fieldInfo.getPropertyType())) {
-					sql.append("='").append(fieldInfo.getLogicNotDeleteValue()).append("'");
-				} else {
-					sql.append("=").append(fieldInfo.getLogicNotDeleteValue());
-				}
-			}
-		}
-		return sql.toString();
-	}
+    /**
+     * <p>
+     * SQL 更新 set 语句
+     * </p>
+     *
+     * @param table 表信息
+     * @return sql and 片段
+     */
+    public String getLogicDeleteSql(TableInfo table) {
+        StringBuilder sql = new StringBuilder();
+        List<TableFieldInfo> fieldList = table.getFieldList();
+        for (TableFieldInfo fieldInfo : fieldList) {
+            if (fieldInfo.isLogicDelete()) {
+                sql.append(" AND ").append(fieldInfo.getColumn());
+                if ("java.lang.String".equals(fieldInfo.getPropertyType())) {
+                    sql.append("='").append(fieldInfo.getLogicNotDeleteValue()).append("'");
+                } else {
+                    sql.append("=").append(fieldInfo.getLogicNotDeleteValue());
+                }
+            }
+        }
+        return sql.toString();
+    }
 
-	/**
-	 * <p>
-	 * SQL 更新 set 语句
-	 * </p>
-	 *
-	 * @param table
-	 *            表信息
-	 * @return sql set 片段
-	 */
-	protected String sqlLogicSet(TableInfo table) {
-		List<TableFieldInfo> fieldList = table.getFieldList();
-		StringBuilder set = new StringBuilder("SET ");
-		int i = 0;
-		for (TableFieldInfo fieldInfo : fieldList) {
-			if (fieldInfo.isLogicDelete()) {
-				if (++i > 1) {
-					set.append(",");
-				}
-				set.append(fieldInfo.getColumn()).append("=");
-				if ("java.lang.String".equals(fieldInfo.getPropertyType())) {
-					set.append("'").append(fieldInfo.getLogicDeleteValue()).append("'");
-				} else {
-					set.append(fieldInfo.getLogicDeleteValue());
-				}
-			}
-		}
-		return set.toString();
-	}
+    /**
+     * <p>
+     * SQL 更新 set 语句
+     * </p>
+     *
+     * @param table 表信息
+     * @return sql set 片段
+     */
+    protected String sqlLogicSet(TableInfo table) {
+        List<TableFieldInfo> fieldList = table.getFieldList();
+        StringBuilder set = new StringBuilder("SET ");
+        int i = 0;
+        for (TableFieldInfo fieldInfo : fieldList) {
+            if (fieldInfo.isLogicDelete()) {
+                if (++i > 1) {
+                    set.append(",");
+                }
+                set.append(fieldInfo.getColumn()).append("=");
+                if ("java.lang.String".equals(fieldInfo.getPropertyType())) {
+                    set.append("'").append(fieldInfo.getLogicDeleteValue()).append("'");
+                } else {
+                    set.append(fieldInfo.getLogicDeleteValue());
+                }
+            }
+        }
+        return set.toString();
+    }
 
-	// ------------ 处理逻辑删除条件过滤 ------------
+    // ------------ 处理逻辑删除条件过滤 ------------
 
-	@Override
-	protected String sqlWhere(TableInfo table) {
-		if (table.isLogicDelete()) {
-			StringBuilder where = new StringBuilder("\n<where>");
-			// 过滤逻辑
-			List<TableFieldInfo> fieldList = table.getFieldList();
-			// EW 逻辑
-			if (StringUtils.isNotEmpty(table.getKeyProperty())) {
-				where.append("\n<if test=\"ew.").append(table.getKeyProperty()).append("!=null\">");
-				where.append(" AND ").append(table.getKeyColumn()).append("=#{ew.");
-				where.append(table.getKeyProperty()).append("}");
-				where.append("</if>");
-			}
-			for (TableFieldInfo fieldInfo : fieldList) {
-				where.append(convertIfTag(fieldInfo, "ew.", false));
-				where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.");
-				where.append(fieldInfo.getEl()).append("}");
-				where.append(convertIfTag(fieldInfo, true));
-			}
-			// 过滤逻辑
-			where.append("\n").append(getLogicDeleteSql(table));
-			where.append("\n</where>");
-			return where.toString();
-		}
-		// 正常逻辑
-		return super.sqlWhere(table);
-	}
+    @Override
+    protected String sqlWhere(TableInfo table) {
+        if (table.isLogicDelete()) {
+            StringBuilder where = new StringBuilder("\n<where>");
+            // 过滤逻辑
+            List<TableFieldInfo> fieldList = table.getFieldList();
+            // EW 逻辑
+            if (StringUtils.isNotEmpty(table.getKeyProperty())) {
+                where.append("\n<if test=\"ew.").append(table.getKeyProperty()).append("!=null\">");
+                where.append(" AND ").append(table.getKeyColumn()).append("=#{ew.");
+                where.append(table.getKeyProperty()).append("}");
+                where.append("</if>");
+            }
+            for (TableFieldInfo fieldInfo : fieldList) {
+                where.append(convertIfTag(fieldInfo, "ew.", false));
+                where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.");
+                where.append(fieldInfo.getEl()).append("}");
+                where.append(convertIfTag(fieldInfo, true));
+            }
+            // 过滤逻辑
+            where.append("\n").append(getLogicDeleteSql(table));
+            where.append("\n</where>");
+            return where.toString();
+        }
+        // 正常逻辑
+        return super.sqlWhere(table);
+    }
 
-	@Override
-	protected String sqlWhereEntityWrapper(TableInfo table) {
-		if (table.isLogicDelete()) {
-			StringBuilder where = new StringBuilder(128);
-			where.append("\n<where>");
-			where.append("\n<if test=\"ew!=null\">");
-			where.append("\n<if test=\"ew.entity!=null\">");
-			if (StringUtils.isNotEmpty(table.getKeyProperty())) {
-				where.append("\n<if test=\"ew.entity.").append(table.getKeyProperty()).append("!=null\">");
-				where.append(" AND ").append(table.getKeyColumn()).append("=#{ew.entity.");
-				where.append(table.getKeyProperty()).append("}");
-				where.append("</if>");
-			}
-			List<TableFieldInfo> fieldList = table.getFieldList();
-			for (TableFieldInfo fieldInfo : fieldList) {
-				where.append(convertIfTag(fieldInfo, "ew.entity.", false));
-				where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.entity.");
-				where.append(fieldInfo.getEl()).append("}");
-				where.append(convertIfTag(fieldInfo, true));
-			}
-			where.append("\n</if>");
-			where.append("\n<if test=\"ew.sqlSegment!=null\">${ew.sqlSegment}\n</if>");
-			where.append("\n</if>");
-			// 过滤逻辑, 这段代码放在这里的原因,第一:不把 逻辑的过滤 放在where条件 第一位, 能够方便利用索引
-			where.append("\n").append(getLogicDeleteSql(table));
-			where.append("\n</where>");
-			return where.toString();
-		}
-		// 正常逻辑
-		return super.sqlWhereEntityWrapper(table);
-	}
+    @Override
+    protected String sqlWhereEntityWrapper(TableInfo table) {
+        if (table.isLogicDelete()) {
+            StringBuilder where = new StringBuilder(128);
+            where.append("\n<where>");
+            where.append("\n<if test=\"ew!=null\">");
+            where.append("\n<if test=\"ew.entity!=null\">");
+            if (StringUtils.isNotEmpty(table.getKeyProperty())) {
+                where.append("\n<if test=\"ew.entity.").append(table.getKeyProperty()).append("!=null\">");
+                where.append(" AND ").append(table.getKeyColumn()).append("=#{ew.entity.");
+                where.append(table.getKeyProperty()).append("}");
+                where.append("</if>");
+            }
+            List<TableFieldInfo> fieldList = table.getFieldList();
+            for (TableFieldInfo fieldInfo : fieldList) {
+                where.append(convertIfTag(fieldInfo, "ew.entity.", false));
+                where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.entity.");
+                where.append(fieldInfo.getEl()).append("}");
+                where.append(convertIfTag(fieldInfo, true));
+            }
+            where.append("\n</if>");
+            where.append("\n<if test=\"ew.sqlSegment!=null\">${ew.sqlSegment}\n</if>");
+            where.append("\n</if>");
+            // 过滤逻辑, 这段代码放在这里的原因,第一:不把 逻辑的过滤 放在where条件 第一位, 能够方便利用索引
+            where.append("\n").append(getLogicDeleteSql(table));
+            where.append("\n</where>");
+            return where.toString();
+        }
+        // 正常逻辑
+        return super.sqlWhereEntityWrapper(table);
+    }
 
 
-	@Override
-	protected String sqlWhereByMap(TableInfo table) {
-		if (table.isLogicDelete()) {
-			StringBuilder where = new StringBuilder();
-			where.append("\n<where>");
-			// MAP 逻辑
-			where.append("\n<if test=\"cm!=null and !cm.isEmpty\">");
-			where.append("\n<foreach collection=\"cm.keys\" item=\"k\" separator=\"AND\">");
-			where.append("\n<if test=\"cm[k] != null\">");
-			where.append(SqlReservedWords.convert(getGlobalConfig(), "\n${k}")).append(" = #{cm[${k}]}");
-			where.append("</if>");
-			where.append("\n</foreach>");
-			where.append("\n</if>");
-			// 过滤逻辑
-			where.append("\n").append(getLogicDeleteSql(table));
-			where.append("\n</where>");
-			return where.toString();
-		}
-		// 正常逻辑
-		return super.sqlWhereByMap(table);
-	}
+    @Override
+    protected String sqlWhereByMap(TableInfo table) {
+        if (table.isLogicDelete()) {
+            StringBuilder where = new StringBuilder();
+            where.append("\n<where>");
+            // MAP 逻辑
+            where.append("\n<if test=\"cm!=null and !cm.isEmpty\">");
+            where.append("\n<foreach collection=\"cm.keys\" item=\"k\" separator=\"AND\">");
+            where.append("\n<if test=\"cm[k] != null\">");
+            where.append(SqlReservedWords.convert(getGlobalConfig(), "\n${k}")).append(" = #{cm[${k}]}");
+            where.append("</if>");
+            where.append("\n</foreach>");
+            where.append("\n</if>");
+            // 过滤逻辑
+            where.append("\n").append(getLogicDeleteSql(table));
+            where.append("\n</where>");
+            return where.toString();
+        }
+        // 正常逻辑
+        return super.sqlWhereByMap(table);
+    }
 
 }

+ 16 - 15
src/main/java/com/baomidou/mybatisplus/mapper/MetaObjectHandler.java

@@ -52,22 +52,22 @@ public abstract class MetaObjectHandler {
     /**
      * Common method to set value for java bean.
      *
-     * @param fieldName java bean property name
-     * @param fieldVal  java bean property value
+     * @param fieldName  java bean property name
+     * @param fieldVal   java bean property value
      * @param metaObject meta object parameter
      */
-    public MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject){
+    public MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject) {
         String[] fieldNames = metaObject.getGetterNames();
         boolean containsEt = false;
-        for(String name:fieldNames){
-            if(META_OBJ_PREFIX.equals(name)){
+        for (String name : fieldNames) {
+            if (META_OBJ_PREFIX.equals(name)) {
                 containsEt = true;
                 break;
             }
         }
-        if(containsEt) {
-            metaObject.setValue(META_OBJ_PREFIX +"."+ fieldName, fieldVal);
-        }else{
+        if (containsEt) {
+            metaObject.setValue(META_OBJ_PREFIX + "." + fieldName, fieldVal);
+        } else {
             metaObject.setValue(fieldName, fieldVal);
         }
         return this;
@@ -75,22 +75,23 @@ public abstract class MetaObjectHandler {
 
     /**
      * get value from java bean by propertyName
-     * @param fieldName java bean property name
+     *
+     * @param fieldName  java bean property name
      * @param metaObject parameter wrapper
      * @return
      */
-    public Object getFieldValByName(String fieldName, MetaObject metaObject){
+    public Object getFieldValByName(String fieldName, MetaObject metaObject) {
         String[] fieldNames = metaObject.getGetterNames();
         boolean containsEt = false;
-        for(String name:fieldNames){
-            if(META_OBJ_PREFIX.equals(name)){
+        for (String name : fieldNames) {
+            if (META_OBJ_PREFIX.equals(name)) {
                 containsEt = true;
                 break;
             }
         }
-        if(containsEt) {
-            return metaObject.getValue(META_OBJ_PREFIX +"."+ fieldName);
-        }else{
+        if (containsEt) {
+            return metaObject.getValue(META_OBJ_PREFIX + "." + fieldName);
+        } else {
             return metaObject.getValue(fieldName);
         }
     }

+ 41 - 40
src/main/java/com/baomidou/mybatisplus/mapper/Wrapper.java

@@ -152,8 +152,8 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param sqlWhere where语句
-     * @param params   参数集
+     * @param sqlWhere  where语句
+     * @param params    参数集
      * @return this
      */
     public Wrapper<T> where(boolean condition, String sqlWhere, Object... params) {
@@ -400,8 +400,8 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param sqlAnd and条件语句
-     * @param params 参数集
+     * @param sqlAnd    and条件语句
+     * @param params    参数集
      * @return this
      */
     public Wrapper<T> and(boolean condition, String sqlAnd, Object... params) {
@@ -433,8 +433,8 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param sqlAnd AND 条件语句
-     * @param params 参数值
+     * @param sqlAnd    AND 条件语句
+     * @param params    参数值
      * @return this
      */
     public Wrapper<T> andNew(boolean condition, String sqlAnd, Object... params) {
@@ -491,8 +491,8 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param sqlOr  or 条件语句
-     * @param params 参数集
+     * @param sqlOr     or 条件语句
+     * @param params    参数集
      * @return this
      */
     public Wrapper<T> or(boolean condition, String sqlOr, Object... params) {
@@ -528,8 +528,8 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param sqlOr  AND 条件语句
-     * @param params 参数值
+     * @param sqlOr     AND 条件语句
+     * @param params    参数值
      * @return this
      */
     public Wrapper<T> orNew(boolean condition, String sqlOr, Object... params) {
@@ -568,7 +568,7 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param columns SQL 中的 Group by 语句,无需输入 Group By 关键字
+     * @param columns   SQL 中的 Group by 语句,无需输入 Group By 关键字
      * @return this
      */
     public Wrapper<T> groupBy(boolean condition, String columns) {
@@ -637,7 +637,7 @@ public abstract class Wrapper<T> implements Serializable {
      * </p>
      *
      * @param condition 拼接的前置条件
-     * @param columns SQL 中的 order by 语句,无需输入 Order By 关键字
+     * @param columns   SQL 中的 order by 语句,无需输入 Order By 关键字
      * @return this
      */
     public Wrapper<T> orderBy(boolean condition, String columns) {
@@ -666,9 +666,10 @@ public abstract class Wrapper<T> implements Serializable {
      * <p>
      * SQL中orderby关键字跟的条件语句,可根据变更动态排序
      * </p>
+     *
      * @param condition 拼接的前置条件
-     * @param columns SQL 中的 order by 语句,无需输入 Order By 关键字
-     * @param isAsc   是否为升序
+     * @param columns   SQL 中的 order by 语句,无需输入 Order By 关键字
+     * @param isAsc     是否为升序
      * @return this
      */
     public Wrapper<T> orderBy(boolean condition, String columns, boolean isAsc) {
@@ -695,8 +696,8 @@ public abstract class Wrapper<T> implements Serializable {
      * LIKE条件语句,value中无需前后%
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值
+     * @param column    字段名称
+     * @param value     匹配值
      * @return this
      */
     public Wrapper<T> like(boolean condition, String column, String value) {
@@ -720,8 +721,8 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT LIKE条件语句,value中无需前后%
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值
+     * @param column    字段名称
+     * @param value     匹配值
      * @return this
      */
     public Wrapper<T> notLike(boolean condition, String column, String value) {
@@ -764,8 +765,8 @@ public abstract class Wrapper<T> implements Serializable {
      * LIKE条件语句,value中无需前后%
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值
+     * @param column    字段名称
+     * @param value     匹配值
      * @param type
      * @return this
      */
@@ -791,8 +792,8 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT LIKE条件语句,value中无需前后%
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值
+     * @param column    字段名称
+     * @param value     匹配值
      * @param type
      * @return this
      */
@@ -818,7 +819,7 @@ public abstract class Wrapper<T> implements Serializable {
      * is not null 条件
      *
      * @param condition 拼接的前置条件
-     * @param columns 字段名称。多个字段以逗号分隔。
+     * @param columns   字段名称。多个字段以逗号分隔。
      * @return this
      */
     public Wrapper<T> isNotNull(boolean condition, String columns) {
@@ -841,7 +842,7 @@ public abstract class Wrapper<T> implements Serializable {
      * is not null 条件
      *
      * @param condition 拼接的前置条件
-     * @param columns 字段名称。多个字段以逗号分隔。
+     * @param columns   字段名称。多个字段以逗号分隔。
      * @return this
      */
     public Wrapper<T> isNull(boolean condition, String columns) {
@@ -864,7 +865,7 @@ public abstract class Wrapper<T> implements Serializable {
      * EXISTS 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param value 匹配值
+     * @param value     匹配值
      * @return this
      */
     public Wrapper<T> exists(boolean condition, String value) {
@@ -887,7 +888,7 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT EXISTS条件语句
      *
      * @param condition 拼接的前置条件
-     * @param value 匹配值
+     * @param value     匹配值
      * @return this
      */
     public Wrapper<T> notExists(boolean condition, String value) {
@@ -910,8 +911,8 @@ public abstract class Wrapper<T> implements Serializable {
      * IN 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  逗号拼接的字符串
+     * @param column    字段名称
+     * @param value     逗号拼接的字符串
      * @return this
      */
     public Wrapper<T> in(boolean condition, String column, String value) {
@@ -936,8 +937,8 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT IN条件语句
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  逗号拼接的字符串
+     * @param column    字段名称
+     * @param value     逗号拼接的字符串
      * @return this
      */
     public Wrapper<T> notIn(boolean condition, String column, String value) {
@@ -962,8 +963,8 @@ public abstract class Wrapper<T> implements Serializable {
      * IN 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值 List集合
+     * @param column    字段名称
+     * @param value     匹配值 List集合
      * @return this
      */
     public Wrapper<T> in(boolean condition, String column, Collection<?> value) {
@@ -987,8 +988,8 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT IN 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值 List集合
+     * @param column    字段名称
+     * @param value     匹配值 List集合
      * @return this
      */
     public Wrapper<T> notIn(boolean condition, String column, Collection<?> value) {
@@ -1012,8 +1013,8 @@ public abstract class Wrapper<T> implements Serializable {
      * IN 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值 object数组
+     * @param column    字段名称
+     * @param value     匹配值 object数组
      * @return this
      */
     public Wrapper<T> in(boolean condition, String column, Object[] value) {
@@ -1037,8 +1038,8 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT IN 条件语句,目前适配mysql及oracle
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
-     * @param value  匹配值 object数组
+     * @param column    字段名称
+     * @param value     匹配值 object数组
      * @return this
      */
     public Wrapper<T> notIn(boolean condition, String column, Object... value) {
@@ -1091,7 +1092,7 @@ public abstract class Wrapper<T> implements Serializable {
      * betwwee 条件语句
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
+     * @param column    字段名称
      * @param val1
      * @param val2
      * @return this
@@ -1118,7 +1119,7 @@ public abstract class Wrapper<T> implements Serializable {
      * NOT betwwee 条件语句
      *
      * @param condition 拼接的前置条件
-     * @param column 字段名称
+     * @param column    字段名称
      * @param val1
      * @param val2
      * @return this

+ 50 - 49
src/main/java/com/baomidou/mybatisplus/plugins/OptimisticLockerInterceptor.java

@@ -29,20 +29,20 @@ import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
 /**
  * <p>
  * Optimistic Lock Light version<BR>
- *     Intercept on {@link Executor}.update;<BR>
- *     Support version types: int/Integer, long/Long, java.util.Date, java.sql.Timestamp<BR>
- *     For extra types, please define a subclass and override {@code getUpdatedVersionVal}() method.<BR>
+ * Intercept on {@link Executor}.update;<BR>
+ * Support version types: int/Integer, long/Long, java.util.Date, java.sql.Timestamp<BR>
+ * For extra types, please define a subclass and override {@code getUpdatedVersionVal}() method.<BR>
  * <BR>
  * How to use?<BR>
- *     (1) Define an Entity and add {@link Version} annotation on one entity field.<BR>
- *     (2) Add {@link OptimisticLockerInterceptor} into mybatis plugin.
- *
+ * (1) Define an Entity and add {@link Version} annotation on one entity field.<BR>
+ * (2) Add {@link OptimisticLockerInterceptor} into mybatis plugin.
+ * <p>
  * How to work?<BR>
- *     if update entity with version column=1:<BR>
- *         (1) no {@link OptimisticLockerInterceptor}:<BR>
- *             SQL: update tbl_test set name='abc' where id=100001;<BR>
- *         (2) add {@link OptimisticLockerInterceptor}:<BR>
- *             SQL: update tbl_test set name='abc',version=2 where id=100001 and version=1;
+ * if update entity with version column=1:<BR>
+ * (1) no {@link OptimisticLockerInterceptor}:<BR>
+ * SQL: update tbl_test set name='abc' where id=100001;<BR>
+ * (2) add {@link OptimisticLockerInterceptor}:<BR>
+ * SQL: update tbl_test set name='abc',version=2 where id=100001 and version=1;
  * </p>
  *
  * @author yuxiaobin
@@ -66,45 +66,45 @@ public class OptimisticLockerInterceptor implements Interceptor {
     public Object intercept(Invocation invocation) throws Throwable {
         Object[] args = invocation.getArgs();
         MappedStatement ms = (MappedStatement) args[0];
-        if(SqlCommandType.UPDATE.compareTo(ms.getSqlCommandType())!=0){
+        if (SqlCommandType.UPDATE.compareTo(ms.getSqlCommandType()) != 0) {
             return invocation.proceed();
         }
         Object param = args[1];
-        if(param instanceof MapperMethod.ParamMap){
+        if (param instanceof MapperMethod.ParamMap) {
             MapperMethod.ParamMap map = (MapperMethod.ParamMap) param;
             Wrapper ew = null;
-            if(map.containsKey(NAME_ENTITY_WRAPPER)){//mapper.update(updEntity, EntityWrapper<>(whereEntity);
+            if (map.containsKey(NAME_ENTITY_WRAPPER)) {//mapper.update(updEntity, EntityWrapper<>(whereEntity);
                 ew = (Wrapper) map.get(NAME_ENTITY_WRAPPER);
             }//else updateById(entity) -->> change updateById(entity) to updateById(@Param("et") entity)
             Object et = map.get(NAME_ENTITY);
-            if(ew!=null){
+            if (ew != null) {
                 Object entity = ew.getEntity();
-                if(entity!=null){
+                if (entity != null) {
                     EntityField ef = getVersionField(entity.getClass());
-                    Field versionField = ef==null?null:ef.getField();
+                    Field versionField = ef == null ? null : ef.getField();
                     if (versionField != null) {
                         Object originalVersionVal = versionField.get(entity);
-                        if(originalVersionVal!=null){
+                        if (originalVersionVal != null) {
                             versionField.set(et, getUpdatedVersionVal(originalVersionVal));
                         }
                     }
                 }
-            }else{
+            } else {
                 String methodId = ms.getId();
-                String updateMethodName = methodId.substring(ms.getId().lastIndexOf(".")+1);
-                if(PARAM_UPDATE_METHOD_NAME.equals(updateMethodName)){//update(entity, null) -->> update all. ignore version
+                String updateMethodName = methodId.substring(ms.getId().lastIndexOf(".") + 1);
+                if (PARAM_UPDATE_METHOD_NAME.equals(updateMethodName)) {//update(entity, null) -->> update all. ignore version
                     return invocation.proceed();
                 }
                 EntityField entityField = getVersionField(et.getClass());
-                Field versionField = entityField==null?null:entityField.getField();
+                Field versionField = entityField == null ? null : entityField.getField();
                 Object originalVersionVal;
-                if(versionField!=null && (originalVersionVal=versionField.get(et))!=null) {
+                if (versionField != null && (originalVersionVal = versionField.get(et)) != null) {
                     TableInfo tableInfo = TableInfoHelper.getTableInfo(et.getClass());
-                    Map<String,Object> entityMap = new HashMap<>();
+                    Map<String, Object> entityMap = new HashMap<>();
                     List<EntityField> fields = getEntityFields(et.getClass());
-                    for(EntityField ef : fields){
+                    for (EntityField ef : fields) {
                         Field fd = ef.getField();
-                        if(fd.isAccessible()) {
+                        if (fd.isAccessible()) {
                             entityMap.put(fd.getName(), fd.get(et));
                             if (ef.isVersion()) {
                                 versionField = fd;
@@ -114,7 +114,7 @@ public class OptimisticLockerInterceptor implements Interceptor {
                     String versionPropertyName = versionField.getName();
                     List<TableFieldInfo> fieldList = tableInfo.getFieldList();
                     String versionColumnName = entityField.getColumnName();
-                    if(versionColumnName==null) {
+                    if (versionColumnName == null) {
                         for (TableFieldInfo tf : fieldList) {
                             if (versionPropertyName.equals(tf.getProperty())) {
                                 versionColumnName = tf.getColumn();
@@ -141,21 +141,21 @@ public class OptimisticLockerInterceptor implements Interceptor {
      * @param originalVersionVal
      * @return updated version val
      */
-    protected Object getUpdatedVersionVal(Object originalVersionVal){
+    protected Object getUpdatedVersionVal(Object originalVersionVal) {
         Class<?> versionValClass = originalVersionVal.getClass();
-        if(long.class.equals(versionValClass)){
-            return ((long)originalVersionVal)+1;
-        }else if(Long.class.equals(versionValClass)){
-            return ((Long)originalVersionVal)+1;
-        }else if(int.class.equals(versionValClass)){
-            return ((int)originalVersionVal)+1;
-        }else if(Integer.class.equals(versionValClass)){
-            return ((Integer)originalVersionVal)+1;
-        }else if(Date.class.equals(versionValClass)){
+        if (long.class.equals(versionValClass)) {
+            return ((long) originalVersionVal) + 1;
+        } else if (Long.class.equals(versionValClass)) {
+            return ((Long) originalVersionVal) + 1;
+        } else if (int.class.equals(versionValClass)) {
+            return ((int) originalVersionVal) + 1;
+        } else if (Integer.class.equals(versionValClass)) {
+            return ((Integer) originalVersionVal) + 1;
+        } else if (Date.class.equals(versionValClass)) {
             return new Date();
-        }else if(Timestamp.class.equals(versionValClass)){
+        } else if (Timestamp.class.equals(versionValClass)) {
             return new Timestamp(System.currentTimeMillis());
-        }else{
+        } else {
             return originalVersionVal;//not supported type, return original val.
         }
     }
@@ -177,7 +177,7 @@ public class OptimisticLockerInterceptor implements Interceptor {
         synchronized (parameterClass.getName()) {
             if (versionFieldCache.containsKey(parameterClass)) {
                 return versionFieldCache.get(parameterClass);
-            }else{
+            } else {
                 EntityField field = getVersionFieldRegular(parameterClass);
                 versionFieldCache.put(parameterClass, field);
                 return field;
@@ -185,7 +185,7 @@ public class OptimisticLockerInterceptor implements Interceptor {
         }
     }
 
-    private EntityField getVersionFieldRegular(Class<?> parameterClass){
+    private EntityField getVersionFieldRegular(Class<?> parameterClass) {
         if (parameterClass != Object.class) {
             for (Field field : parameterClass.getDeclaredFields()) {
                 if (field.isAnnotationPresent(Version.class)) {
@@ -198,26 +198,26 @@ public class OptimisticLockerInterceptor implements Interceptor {
         return null;
     }
 
-    private List<EntityField> getEntityFields(Class<?> parameterClass){
-        if(entityFieldsCache.containsKey(parameterClass)){
+    private List<EntityField> getEntityFields(Class<?> parameterClass) {
+        if (entityFieldsCache.containsKey(parameterClass)) {
             return entityFieldsCache.get(parameterClass);
-        }else{
+        } else {
             List<EntityField> fields = getFieldsFromClazz(parameterClass, null);
             entityFieldsCache.put(parameterClass, fields);
             return fields;
         }
     }
 
-    private List<EntityField> getFieldsFromClazz(Class<?> parameterClass, List<EntityField> fieldList){
-        if(fieldList==null){
+    private List<EntityField> getFieldsFromClazz(Class<?> parameterClass, List<EntityField> fieldList) {
+        if (fieldList == null) {
             fieldList = new ArrayList<>();
         }
         List<Field> fields = ReflectionKit.getFieldList(parameterClass);
-        for(Field field:fields){
+        for (Field field : fields) {
             field.setAccessible(true);
             if (field.isAnnotationPresent(Version.class)) {
                 fieldList.add(new EntityField(field, true));
-            }else{
+            } else {
                 fieldList.add(new EntityField(field, false));
             }
         }
@@ -225,7 +225,8 @@ public class OptimisticLockerInterceptor implements Interceptor {
     }
 
 }
-class EntityField{
+
+class EntityField {
 
     private Field field;
     private boolean version;

+ 5 - 4
src/main/java/com/baomidou/mybatisplus/plugins/PerformanceInterceptor.java

@@ -51,6 +51,7 @@ import com.baomidou.mybatisplus.toolkit.SystemClock;
         @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
         @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
 public class PerformanceInterceptor implements Interceptor {
+
     private static final Log logger = LogFactory.getLog(PerformanceInterceptor.class);
     /**
      * SQL 执行最大时长,超过自动停止运行,有助于发现问题。
@@ -88,14 +89,14 @@ public class PerformanceInterceptor implements Interceptor {
 
         String originalSql = null;
         String stmtClassName = statement.getClass().getName();
-        if("oracle.jdbc.driver.T4CPreparedStatement".equals(stmtClassName)){
+        if ("oracle.jdbc.driver.T4CPreparedStatement".equals(stmtClassName)) {
             try {
-                if(oracleGetOriginalSqlMethod!=null){
+                if (oracleGetOriginalSqlMethod != null) {
                     Object stmtSql = oracleGetOriginalSqlMethod.invoke(statement);
                     if (stmtSql != null && stmtSql instanceof String) {
                         originalSql = (String) stmtSql;
                     }
-                }else {
+                } else {
                     Class<?> clazz = Class.forName("oracle.jdbc.driver.OracleStatement");
                     oracleGetOriginalSqlMethod = clazz.getDeclaredMethod("getOriginalSql", null);
                     if (oracleGetOriginalSqlMethod != null) {
@@ -108,7 +109,7 @@ public class PerformanceInterceptor implements Interceptor {
             } catch (Exception e) {//ignore
             }
         }
-        if(originalSql==null){
+        if (originalSql == null) {
             originalSql = statement.toString();
         }
 

+ 7 - 14
src/main/java/com/baomidou/mybatisplus/plugins/pagination/DialectFactory.java

@@ -46,14 +46,10 @@ public class DialectFactory {
      * 生成翻页执行 SQL
      * </p>
      *
-     * @param page
-     *            翻页对象
-     * @param buildSql
-     *            执行 SQL
-     * @param dialectType
-     *            方言类型
-     * @param dialectClazz
-     *            自定义方言实现类
+     * @param page         翻页对象
+     * @param buildSql     执行 SQL
+     * @param dialectType  方言类型
+     * @param dialectClazz 自定义方言实现类
      * @return
      * @throws Exception
      */
@@ -85,10 +81,8 @@ public class DialectFactory {
      * 获取数据库方言
      * </p>
      *
-     * @param dialectType
-     *            方言类型
-     * @param dialectClazz
-     *            自定义方言实现类
+     * @param dialectType  方言类型
+     * @param dialectClazz 自定义方言实现类
      * @return
      * @throws Exception
      */
@@ -120,8 +114,7 @@ public class DialectFactory {
      * 根据数据库类型选择不同分页方言
      * </p>
      *
-     * @param dbType
-     *            数据库类型
+     * @param dbType 数据库类型
      * @return
      * @throws Exception
      */

+ 3 - 6
src/main/java/com/baomidou/mybatisplus/plugins/pagination/IDialect.java

@@ -28,12 +28,9 @@ public interface IDialect {
     /**
      * 组装分页语句
      *
-     * @param originalSql
-     *            原始语句
-     * @param offset
-     *            偏移量
-     * @param limit
-     *            界限
+     * @param originalSql 原始语句
+     * @param offset      偏移量
+     * @param limit       界限
      * @return 分页语句
      */
     String buildPaginationSql(String originalSql, int offset, int limit);

+ 2 - 5
src/main/java/com/baomidou/mybatisplus/plugins/pagination/Pagination.java

@@ -61,7 +61,6 @@ public class Pagination extends RowBounds implements Serializable {
      * 查询总数优化(默认 false 该属性只针对于Optimize.DEFAULT有效)
      *
      * @see com.baomidou.mybatisplus.enums.Optimize
-     *
      */
     private boolean optimizeCount = false;
 
@@ -90,10 +89,8 @@ public class Pagination extends RowBounds implements Serializable {
      * 分页构造函数
      * </p>
      *
-     * @param current
-     *            当前页
-     * @param size
-     *            每页显示条数
+     * @param current 当前页
+     * @param size    每页显示条数
      */
     public Pagination(int current, int size) {
         this(current, size, true);

+ 14 - 0
src/main/java/com/baomidou/mybatisplus/plugins/pagination/dialects/DB2Dialect.java

@@ -14,6 +14,20 @@
  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  * License for the specific language governing permissions and limitations under
  * the License.
+ * <p>
+ * Copyright (c) 2011-2014, hubin (jobob@qq.com).
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
  */
 /**
  * Copyright (c) 2011-2014, hubin (jobob@qq.com).

+ 34 - 69
src/main/java/com/baomidou/mybatisplus/service/IService.java

@@ -37,8 +37,7 @@ public interface IService<T> {
      * 插入一条记录(选择字段,策略插入)
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return boolean
      */
     boolean insert(T entity);
@@ -48,8 +47,7 @@ public interface IService<T> {
      * 插入一条记录(全部字段)
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return boolean
      */
     boolean insertAllColumn(T entity);
@@ -59,8 +57,7 @@ public interface IService<T> {
      * 插入(批量),该方法不适合 Oracle
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
+     * @param entityList 实体对象列表
      * @return boolean
      */
     boolean insertBatch(List<T> entityList);
@@ -70,10 +67,8 @@ public interface IService<T> {
      * 插入(批量)
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
-     * @param batchSize
-     *            插入批次数量
+     * @param entityList 实体对象列表
+     * @param batchSize  插入批次数量
      * @return boolean
      */
     boolean insertBatch(List<T> entityList, int batchSize);
@@ -83,8 +78,7 @@ public interface IService<T> {
      * 批量修改插入
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
+     * @param entityList 实体对象列表
      * @return boolean
      */
     boolean insertOrUpdateBatch(List<T> entityList);
@@ -94,10 +88,8 @@ public interface IService<T> {
      * 批量修改插入
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
+     * @param entityList 实体对象列表
      * @param batchSize
-     *
      * @return boolean
      */
     boolean insertOrUpdateBatch(List<T> entityList, int batchSize);
@@ -107,8 +99,7 @@ public interface IService<T> {
      * 根据 ID 删除
      * </p>
      *
-     * @param id
-     *            主键ID
+     * @param id 主键ID
      * @return boolean
      */
     boolean deleteById(Serializable id);
@@ -118,8 +109,7 @@ public interface IService<T> {
      * 根据 columnMap 条件,删除记录
      * </p>
      *
-     * @param columnMap
-     *            表字段 map 对象
+     * @param columnMap 表字段 map 对象
      * @return boolean
      */
     boolean deleteByMap(Map<String, Object> columnMap);
@@ -129,8 +119,7 @@ public interface IService<T> {
      * 根据 entity 条件,删除记录
      * </p>
      *
-     * @param wrapper
-     *            实体包装类 {@link Wrapper}
+     * @param wrapper 实体包装类 {@link Wrapper}
      * @return boolean
      */
     boolean delete(Wrapper<T> wrapper);
@@ -140,8 +129,7 @@ public interface IService<T> {
      * 删除(根据ID 批量删除)
      * </p>
      *
-     * @param idList
-     *            主键ID列表
+     * @param idList 主键ID列表
      * @return boolean
      */
     boolean deleteBatchIds(List<? extends Serializable> idList);
@@ -151,8 +139,7 @@ public interface IService<T> {
      * 根据 ID 选择修改
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return boolean
      */
     boolean updateById(T entity);
@@ -162,8 +149,7 @@ public interface IService<T> {
      * 根据 ID 修改全部字段
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return boolean
      */
     boolean updateAllColumnById(T entity);
@@ -173,10 +159,8 @@ public interface IService<T> {
      * 根据 whereEntity 条件,更新记录
      * </p>
      *
-     * @param entity
-     *            实体对象
-     * @param wrapper
-     *            实体包装类 {@link Wrapper}
+     * @param entity  实体对象
+     * @param wrapper 实体包装类 {@link Wrapper}
      * @return boolean
      */
     boolean update(T entity, Wrapper<T> wrapper);
@@ -186,8 +170,7 @@ public interface IService<T> {
      * 根据ID 批量更新
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
+     * @param entityList 实体对象列表
      * @return boolean
      */
     boolean updateBatchById(List<T> entityList);
@@ -197,10 +180,8 @@ public interface IService<T> {
      * 根据ID 批量更新
      * </p>
      *
-     * @param entityList
-     *            实体对象列表
-     * @param batchSize
-     *            更新批次数量
+     * @param entityList 实体对象列表
+     * @param batchSize  更新批次数量
      * @return boolean
      */
     boolean updateBatchById(List<T> entityList, int batchSize);
@@ -210,8 +191,7 @@ public interface IService<T> {
      * TableId 注解存在更新记录,否插入一条记录
      * </p>
      *
-     * @param entity
-     *            实体对象
+     * @param entity 实体对象
      * @return boolean
      */
     boolean insertOrUpdate(T entity);
@@ -221,8 +201,7 @@ public interface IService<T> {
      * 根据 ID 查询
      * </p>
      *
-     * @param id
-     *            主键ID
+     * @param id 主键ID
      * @return T
      */
     T selectById(Serializable id);
@@ -232,8 +211,7 @@ public interface IService<T> {
      * 查询(根据ID 批量查询)
      * </p>
      *
-     * @param idList
-     *            主键ID列表
+     * @param idList 主键ID列表
      * @return List<T>
      */
     List<T> selectBatchIds(List<? extends Serializable> idList);
@@ -243,8 +221,7 @@ public interface IService<T> {
      * 查询(根据 columnMap 条件)
      * </p>
      *
-     * @param columnMap
-     *            表字段 map 对象
+     * @param columnMap 表字段 map 对象
      * @return List<T>
      */
     List<T> selectByMap(Map<String, Object> columnMap);
@@ -254,8 +231,7 @@ public interface IService<T> {
      * 根据 Wrapper,查询一条记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象
+     * @param wrapper 实体对象
      * @return T
      */
     T selectOne(Wrapper<T> wrapper);
@@ -265,8 +241,7 @@ public interface IService<T> {
      * 根据 Wrapper,查询一条记录
      * </p>
      *
-     * @param wrapper
-     *            {@link Wrapper}
+     * @param wrapper {@link Wrapper}
      * @return Map<String,Object>
      */
     Map<String, Object> selectMap(Wrapper<T> wrapper);
@@ -276,8 +251,7 @@ public interface IService<T> {
      * 根据 Wrapper,查询一条记录
      * </p>
      *
-     * @param wrapper
-     *            {@link Wrapper}
+     * @param wrapper {@link Wrapper}
      * @return Object
      */
     Object selectObj(Wrapper<T> wrapper);
@@ -287,8 +261,7 @@ public interface IService<T> {
      * 根据 Wrapper 条件,查询总记录数
      * </p>
      *
-     * @param wrapper
-     *            实体对象
+     * @param wrapper 实体对象
      * @return int
      */
     int selectCount(Wrapper<T> wrapper);
@@ -298,8 +271,7 @@ public interface IService<T> {
      * 查询列表
      * </p>
      *
-     * @param wrapper
-     *            实体包装类 {@link Wrapper}
+     * @param wrapper 实体包装类 {@link Wrapper}
      * @return
      */
     List<T> selectList(Wrapper<T> wrapper);
@@ -309,8 +281,7 @@ public interface IService<T> {
      * 翻页查询
      * </p>
      *
-     * @param page
-     *            翻页对象
+     * @param page 翻页对象
      * @return
      */
     Page<T> selectPage(Page<T> page);
@@ -320,8 +291,7 @@ public interface IService<T> {
      * 查询列表
      * </p>
      *
-     * @param wrapper
-     *            {@link Wrapper}
+     * @param wrapper {@link Wrapper}
      * @return
      */
     List<Map<String, Object>> selectMaps(Wrapper<T> wrapper);
@@ -331,8 +301,7 @@ public interface IService<T> {
      * 根据 Wrapper 条件,查询全部记录
      * </p>
      *
-     * @param wrapper
-     *            实体对象封装操作类(可以为 null)
+     * @param wrapper 实体对象封装操作类(可以为 null)
      * @return List<Object>
      */
     List<Object> selectObjs(Wrapper<T> wrapper);
@@ -342,10 +311,8 @@ public interface IService<T> {
      * 翻页查询
      * </p>
      *
-     * @param page
-     *            翻页对象
-     * @param wrapper
-     *            {@link Wrapper}
+     * @param page    翻页对象
+     * @param wrapper {@link Wrapper}
      * @return
      */
     @SuppressWarnings("rawtypes")
@@ -356,10 +323,8 @@ public interface IService<T> {
      * 翻页查询
      * </p>
      *
-     * @param page
-     *            翻页对象
-     * @param wrapper
-     *            实体包装类 {@link Wrapper}
+     * @param page    翻页对象
+     * @param wrapper 实体包装类 {@link Wrapper}
      * @return
      */
     Page<T> selectPage(Page<T> page, Wrapper<T> wrapper);

+ 1 - 1
src/main/java/com/baomidou/mybatisplus/service/impl/ServiceImpl.java

@@ -250,7 +250,7 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
             String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
             for (int i = 0; i < size; i++) {
                 MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
-                param.put("et",entityList.get(i));
+                param.put("et", entityList.get(i));
                 batchSqlSession.update(sqlStatement, param);
                 if (i >= 1 && i % batchSize == 0) {
                     batchSqlSession.flushStatements();

+ 3 - 1
src/main/java/com/baomidou/mybatisplus/spring/MybatisMapperRefresh.java

@@ -86,6 +86,7 @@ public class MybatisMapperRefresh implements Runnable {
 
     /**
      * see  com.baomidou.mybatisplus.spring.MybatisMapperRefresh#MybatisMapperRefresh(org.apache.ibatis.session.SqlSessionFactory, int, int, boolean)
+     *
      * @param mapperLocations
      * @param sqlSessionFactory
      * @param delaySeconds
@@ -106,6 +107,7 @@ public class MybatisMapperRefresh implements Runnable {
 
     /**
      * see com.baomidou.mybatisplus.spring.MybatisMapperRefresh#MybatisMapperRefresh(org.apache.ibatis.session.SqlSessionFactory, boolean)
+     *
      * @param mapperLocations
      * @param sqlSessionFactory
      * @param enabled
@@ -126,7 +128,7 @@ public class MybatisMapperRefresh implements Runnable {
         this.run();
     }
 
-    public MybatisMapperRefresh(SqlSessionFactory sqlSessionFactory,int delaySeconds, int sleepSeconds,boolean enabled) throws Exception {
+    public MybatisMapperRefresh(SqlSessionFactory sqlSessionFactory, int delaySeconds, int sleepSeconds, boolean enabled) throws Exception {
         this.sqlSessionFactory = sqlSessionFactory;
         this.delaySeconds = delaySeconds;
         this.sleepSeconds = sleepSeconds;

+ 18 - 16
src/main/java/com/baomidou/mybatisplus/spring/MybatisSqlSessionFactoryBean.java

@@ -15,12 +15,18 @@
  */
 package com.baomidou.mybatisplus.spring;
 
-import com.baomidou.mybatisplus.MybatisConfiguration;
-import com.baomidou.mybatisplus.MybatisXMLConfigBuilder;
-import com.baomidou.mybatisplus.entity.GlobalConfiguration;
-import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
-import com.baomidou.mybatisplus.mapper.SqlRunner;
-import com.baomidou.mybatisplus.toolkit.PackageHelper;
+import static org.springframework.util.Assert.notNull;
+import static org.springframework.util.Assert.state;
+import static org.springframework.util.ObjectUtils.isEmpty;
+import static org.springframework.util.StringUtils.hasLength;
+import static org.springframework.util.StringUtils.tokenizeToStringArray;
+
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
 import org.apache.ibatis.builder.xml.XMLMapperBuilder;
 import org.apache.ibatis.cache.Cache;
 import org.apache.ibatis.executor.ErrorContext;
@@ -49,16 +55,12 @@ import org.springframework.core.NestedIOException;
 import org.springframework.core.io.Resource;
 import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
 
-import javax.sql.DataSource;
-import java.io.IOException;
-import java.sql.SQLException;
-import java.util.Properties;
-
-import static org.springframework.util.Assert.notNull;
-import static org.springframework.util.Assert.state;
-import static org.springframework.util.ObjectUtils.isEmpty;
-import static org.springframework.util.StringUtils.hasLength;
-import static org.springframework.util.StringUtils.tokenizeToStringArray;
+import com.baomidou.mybatisplus.MybatisConfiguration;
+import com.baomidou.mybatisplus.MybatisXMLConfigBuilder;
+import com.baomidou.mybatisplus.entity.GlobalConfiguration;
+import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
+import com.baomidou.mybatisplus.mapper.SqlRunner;
+import com.baomidou.mybatisplus.toolkit.PackageHelper;
 
 /**
  * <p>

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/toolkit/JdbcUtils.java

@@ -32,8 +32,7 @@ public class JdbcUtils {
      * 根据连接地址判断数据库类型
      * </p>
      *
-     * @param jdbcUrl
-     *            连接地址
+     * @param jdbcUrl 连接地址
      * @return
      */
     public static DBType getDbType(String jdbcUrl) {

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/toolkit/JsqlParserUtils.java

@@ -47,8 +47,7 @@ public class JsqlParserUtils {
     /**
      * jsqlparser方式获取select的count语句
      *
-     * @param originalSql
-     *            selectSQL
+     * @param originalSql selectSQL
      * @return
      */
     public static CountOptimize jsqlparserCount(CountOptimize countOptimize, String originalSql) {

+ 1 - 2
src/main/java/com/baomidou/mybatisplus/toolkit/PackageHelper.java

@@ -46,8 +46,7 @@ public class PackageHelper {
      * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
      * </p>
      *
-     * @param typeAliasesPackage
-     *            类别名包路径
+     * @param typeAliasesPackage 类别名包路径
      * @return
      */
     public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {

+ 5 - 6
src/main/java/com/baomidou/mybatisplus/toolkit/Sequence.java

@@ -65,10 +65,8 @@ public class Sequence {
     }
 
     /**
-     * @param workerId
-     *            工作机器ID
-     * @param datacenterId
-     *            序列号
+     * @param workerId     工作机器ID
+     * @param datacenterId 序列号
      */
     public Sequence(long workerId, long datacenterId) {
         if (workerId > maxWorkerId || workerId < 0) {
@@ -93,7 +91,7 @@ public class Sequence {
         String name = ManagementFactory.getRuntimeMXBean().getName();
         if (StringUtils.isNotEmpty(name)) {
             /*
-			 * GET jvmPid
+             * GET jvmPid
 			 */
             mpid.append(name.split("@")[0]);
         }
@@ -128,6 +126,7 @@ public class Sequence {
 
     /**
      * 获取下一个ID
+     *
      * @return
      */
     public synchronized long nextId() {
@@ -158,7 +157,7 @@ public class Sequence {
             }
         } else {
             // 不同毫秒内,序列号置为 1 - 3 随机数
-            sequence = ThreadLocalRandom.current().nextLong(1,3);
+            sequence = ThreadLocalRandom.current().nextLong(1, 3);
         }
 
         lastTimestamp = timestamp;

+ 8 - 10
src/main/java/com/baomidou/mybatisplus/toolkit/SqlReservedWords.java

@@ -156,23 +156,21 @@ public class SqlReservedWords {
      * 数据库字段转义
      * </p>
      *
-     * @param globalConfig
-     *            全局配置
-     * @param column
-     *            数据库字段
+     * @param globalConfig 全局配置
+     * @param column       数据库字段
      * @return
      */
     public static String convert(GlobalConfiguration globalConfig, String column) {
-		return containsWord(column) ? convertQuote(globalConfig, column) : column;
+        return containsWord(column) ? convertQuote(globalConfig, column) : column;
     }
 
-	public static String convertQuote(GlobalConfiguration globalConfig, String column) {
-		String identifierQuote = globalConfig.getIdentifierQuote();
+    public static String convertQuote(GlobalConfiguration globalConfig, String column) {
+        String identifierQuote = globalConfig.getIdentifierQuote();
         if (null != identifierQuote) {
             return String.format(identifierQuote, column);
-		}
-		return column;
-	}
+        }
+        return column;
+    }
 
     /**
      * 判断关键字中是否包含该字段

+ 7 - 14
src/main/java/com/baomidou/mybatisplus/toolkit/SqlUtils.java

@@ -36,12 +36,9 @@ public class SqlUtils {
     /**
      * 获取CountOptimize
      *
-     * @param originalSql
-     *            需要计算Count SQL
-     * @param optimizeType
-     *            count优化方式
-     * @param isOptimizeCount
-     *            是否需要优化Count
+     * @param originalSql     需要计算Count SQL
+     * @param optimizeType    count优化方式
+     * @param isOptimizeCount 是否需要优化Count
      * @return CountOptimize
      */
     public static CountOptimize getCountOptimize(String originalSql, String optimizeType, String dialectType,
@@ -109,12 +106,9 @@ public class SqlUtils {
     /**
      * 查询SQL拼接Order By
      *
-     * @param originalSql
-     *            需要拼接的SQL
-     * @param page
-     *            page对象
-     * @param orderBy
-     *            是否需要拼接Order By
+     * @param originalSql 需要拼接的SQL
+     * @param page        page对象
+     * @param orderBy     是否需要拼接Order By
      * @return
      */
     public static String concatOrderBy(String originalSql, Pagination page, boolean orderBy) {
@@ -147,8 +141,7 @@ public class SqlUtils {
      * 用%连接like
      * </p>
      *
-     * @param str
-     *            原字符串
+     * @param str 原字符串
      * @return
      */
     public static String concatLike(String str, SqlLike type) {

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/EntityWrapperTest.java

@@ -64,7 +64,7 @@ public class EntityWrapperTest {
     @Test
     public void test11() {
         /*
-		 * 实体带where ifneed
+         * 实体带where ifneed
 		 */
         ew.setEntity(new User(1));
         ew.where("name={0}", "'123'").addFilterIfNeed(false, "id=12");

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/GlobalConfigurationTest.java

@@ -101,8 +101,8 @@ public class GlobalConfigurationTest {
 
 
     @org.junit.Test
-    public void testStringFormat(){
+    public void testStringFormat() {
         String str = "'%s'";
-        System.out.println(String.format(str,"abc"));
+        System.out.println(String.format(str, "abc"));
     }
 }

+ 55 - 55
src/test/java/com/baomidou/mybatisplus/test/IdWorkerTest.java

@@ -41,63 +41,63 @@ import com.baomidou.mybatisplus.toolkit.IdWorker;
  */
 public class IdWorkerTest {
 
-	@Test
-	public void test() throws Exception {
-		int count = 1000;
-		System.err.println("共有" + count + "个数参与测试");
+    @Test
+    public void test() throws Exception {
+        int count = 1000;
+        System.err.println("共有" + count + "个数参与测试");
 
-		ExecutorService executorService = Executors.newFixedThreadPool(20);
-		final List<Long> results = new ArrayList<>();
-		CompletionService<Long> cs = new ExecutorCompletionService<>(executorService);
-		for (int i = 1; i < count; i++) {
-			cs.submit(new Callable<Long>() {
-				public Long call() throws Exception {
-					Thread.sleep(RandomUtils.nextInt(1, 2000));
-					return IdWorker.getId();
-				}
-			});
-		}
-		for (int i = 0; i < count; i++) {
-			Future<Long> future = executorService.submit(new Callable<Long>() {
-				@Override
-				public Long call() throws Exception {
-					return IdWorker.getId();
-				}
-			});
-			results.add(future.get());
-		}
-		executorService.shutdown();
-		HashSet<Long> set = new HashSet<>(results);
-		// 判断是否有重复
-		Assert.assertEquals(count, set.size());
-		int odd = 0;
-		int even = 0;
-		for (Long id : results) {
-			if (id % 2 != 0) {
-				odd++;
-			} else {
-				even++;
-			}
-		}
-		System.err.println("奇数:" + odd);
-		System.err.println("偶数:" + even);
-	}
+        ExecutorService executorService = Executors.newFixedThreadPool(20);
+        final List<Long> results = new ArrayList<>();
+        CompletionService<Long> cs = new ExecutorCompletionService<>(executorService);
+        for (int i = 1; i < count; i++) {
+            cs.submit(new Callable<Long>() {
+                public Long call() throws Exception {
+                    Thread.sleep(RandomUtils.nextInt(1, 2000));
+                    return IdWorker.getId();
+                }
+            });
+        }
+        for (int i = 0; i < count; i++) {
+            Future<Long> future = executorService.submit(new Callable<Long>() {
+                @Override
+                public Long call() throws Exception {
+                    return IdWorker.getId();
+                }
+            });
+            results.add(future.get());
+        }
+        executorService.shutdown();
+        HashSet<Long> set = new HashSet<>(results);
+        // 判断是否有重复
+        Assert.assertEquals(count, set.size());
+        int odd = 0;
+        int even = 0;
+        for (Long id : results) {
+            if (id % 2 != 0) {
+                odd++;
+            } else {
+                even++;
+            }
+        }
+        System.err.println("奇数:" + odd);
+        System.err.println("偶数:" + even);
+    }
 
-	@Test
-	public void test1() throws Exception {
-		// 毫秒内并发
-		for (int i = 0; i < 1000; i++) {
-			System.out.println(IdWorker.getId());
-		}
-	}
+    @Test
+    public void test1() throws Exception {
+        // 毫秒内并发
+        for (int i = 0; i < 1000; i++) {
+            System.out.println(IdWorker.getId());
+        }
+    }
 
 
-	@Test
-	public void test2() throws Exception {
-		// 随机尾数
-		for (int i = 0; i < 1000; i++) {
-			Thread.sleep(10);
-			System.out.println(IdWorker.getId());
-		}
-	}
+    @Test
+    public void test2() throws Exception {
+        // 随机尾数
+        for (int i = 0; i < 1000; i++) {
+            Thread.sleep(10);
+            System.out.println(IdWorker.getId());
+        }
+    }
 }

+ 60 - 59
src/test/java/com/baomidou/mybatisplus/test/SnowFlake.java

@@ -1,70 +1,71 @@
 package com.baomidou.mybatisplus.test;
 
 public class SnowFlake {
-  // 向左偏移10位
-  public static final long NODE_SHIFT = 10L;
-  // 向左偏移12位
-  public static final long SEQUENCE_SHIFT = 12l;
-  // 最大机器值
-  public static final long MAX_NODE = -1L ^ (-1L << NODE_SHIFT);
-  // 最大序列值
-  public static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_SHIFT);
-  // 机器id
-  private long node;
-  // 序列
-  private long sequence;
-  // 最后一次取id的时间戳
-  private long referenceTime;
 
-  // 初始化如果没有指定node随机生成一个1-最大机器值之间的值
-  public SnowFlake() {
-    this.node = 1l + (long) (Math.random() * MAX_NODE);
-  }
+    // 向左偏移10位
+    public static final long NODE_SHIFT = 10L;
+    // 向左偏移12位
+    public static final long SEQUENCE_SHIFT = 12l;
+    // 最大机器值
+    public static final long MAX_NODE = -1L ^ (-1L << NODE_SHIFT);
+    // 最大序列值
+    public static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_SHIFT);
+    // 机器id
+    private long node;
+    // 序列
+    private long sequence;
+    // 最后一次取id的时间戳
+    private long referenceTime;
 
-  // 初始化指定每台编号避免不同的机器在同一时间生成一样的id
-  public SnowFlake(long node) {
-    if (node >= MAX_NODE || node < 0) throw new IllegalArgumentException(
-        String.format("node can't be greater than %d or less than 0", MAX_NODE));
-    this.node = node;
-  }
+    // 初始化如果没有指定node随机生成一个1-最大机器值之间的值
+    public SnowFlake() {
+        this.node = 1l + (long) (Math.random() * MAX_NODE);
+    }
 
-  // 生成下一个id(线程安全)
-  public synchronized long next() {
-    // 获取1970年1月1日0时起的毫秒差
-    long currentTime = System.currentTimeMillis();
-    // 序列当前值
-    long counter;
-    // 当前时间不能小于最后取id时间(毫秒差会随时间增长,说明系统时钟回退过)
-    if (currentTime < referenceTime) {
-      throw new RuntimeException(String.format("Last referenceTime %s is after reference time %s",
-          referenceTime, currentTime));
+    // 初始化指定每台编号避免不同的机器在同一时间生成一样的id
+    public SnowFlake(long node) {
+        if (node >= MAX_NODE || node < 0) throw new IllegalArgumentException(
+                String.format("node can't be greater than %d or less than 0", MAX_NODE));
+        this.node = node;
     }
-    // 大与最后时间戳序列归零
-    else if (currentTime > referenceTime) {
-      this.sequence = 0l;
-    } else {
-      // 序列小于最大值自增
-      if (this.sequence <= SnowFlake.MAX_SEQUENCE) {
-        this.sequence++;
-      }
-      // 序列溢出
-      else {
-        // 阻塞到下一个毫秒,获得新时间戳
-        while (currentTime <= referenceTime) {
-          currentTime = System.currentTimeMillis();
+
+    // 生成下一个id(线程安全)
+    public synchronized long next() {
+        // 获取1970年1月1日0时起的毫秒差
+        long currentTime = System.currentTimeMillis();
+        // 序列当前值
+        long counter;
+        // 当前时间不能小于最后取id时间(毫秒差会随时间增长,说明系统时钟回退过)
+        if (currentTime < referenceTime) {
+            throw new RuntimeException(String.format("Last referenceTime %s is after reference time %s",
+                    referenceTime, currentTime));
+        }
+        // 大与最后时间戳序列归零
+        else if (currentTime > referenceTime) {
+            this.sequence = 0l;
+        } else {
+            // 序列小于最大值自增
+            if (this.sequence <= SnowFlake.MAX_SEQUENCE) {
+                this.sequence++;
+            }
+            // 序列溢出
+            else {
+                // 阻塞到下一个毫秒,获得新时间戳
+                while (currentTime <= referenceTime) {
+                    currentTime = System.currentTimeMillis();
+                }
+                /**
+                 * 在新的时间戳获取下一个id 关于重复阻塞:缩小机器标识值,增大序列最大值
+                 */
+                next();
+            }
         }
-        /**
-         * 在新的时间戳获取下一个id 关于重复阻塞:缩小机器标识值,增大序列最大值
-         */
-        next();
-      }
+        // 记录当前值
+        counter = this.sequence;
+        // 记录最后生成id时间戳
+        referenceTime = currentTime;
+        // 移位并通过或运算拼到一起组成64位的ID
+        return currentTime << NODE_SHIFT << SEQUENCE_SHIFT | node << SEQUENCE_SHIFT | counter;
     }
-    // 记录当前值
-    counter = this.sequence;
-    // 记录最后生成id时间戳
-    referenceTime = currentTime;
-    // 移位并通过或运算拼到一起组成64位的ID
-    return currentTime << NODE_SHIFT << SEQUENCE_SHIFT | node << SEQUENCE_SHIFT | counter;
-  }
 
 }

+ 6 - 1
src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java

@@ -22,7 +22,12 @@ import java.util.Map;
 
 import com.baomidou.mybatisplus.generator.AutoGenerator;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
-import com.baomidou.mybatisplus.generator.config.*;
+import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
+import com.baomidou.mybatisplus.generator.config.FileOutConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.PackageConfig;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.TemplateConfig;
 import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/h2/H2MetaObjectHandlerTest.java

@@ -85,13 +85,13 @@ public class H2MetaObjectHandlerTest {
     H2UserMetaobjMapper userMapper;
 
     @Test
-    public void testMetaObjectHandler(){
+    public void testMetaObjectHandler() {
         H2UserMetaObj user = new H2UserMetaObj();
         user.setName("metaobjtest");
         user.setVersion(1);
         user.setAge(12);
         Calendar cal = Calendar.getInstance();
-        cal.add(Calendar.DAY_OF_MONTH,-1);
+        cal.add(Calendar.DAY_OF_MONTH, -1);
         user.setLastUpdatedDt(new Timestamp(cal.getTimeInMillis()));
         user.setDesc("abc");
         userMapper.insert(user);

+ 7 - 6
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserAddrJoinTest.java

@@ -64,13 +64,14 @@ public class H2UserAddrJoinTest {
         ) {
             String line;
             while ((line = reader.readLine()) != null) {
-                if(line.isEmpty()){
+                if (line.isEmpty()) {
                     continue;
                 }
                 stmt.execute(line.replace(";", ""));
             }
         }
     }
+
     private static void insertAddr(Statement stmt) throws SQLException, IOException {
         String filename = "addr.insert.sql";
         String filePath = H2UserAddrJoinTest.class.getClassLoader().getResource("").getPath() + "/h2/" + filename;
@@ -79,7 +80,7 @@ public class H2UserAddrJoinTest {
         ) {
             String line;
             while ((line = reader.readLine()) != null) {
-                if(line.isEmpty()){
+                if (line.isEmpty()) {
                     continue;
                 }
                 stmt.execute(line.replace(";", ""));
@@ -104,16 +105,16 @@ public class H2UserAddrJoinTest {
 
 
     @Test
-    public void testJoinTableWithoutPagination(){
+    public void testJoinTableWithoutPagination() {
         List<H2Addr> addrList = userMapper.getAddrListByUserId(101L);
         Assert.assertEquals(5, addrList.size());
     }
+
     @Test
-    public void testJoinTableWithPagination(){
-        List<H2Addr> addrList = userMapper.getAddrListByUserId(101L, new Page<H2Addr>(0,3));
+    public void testJoinTableWithPagination() {
+        List<H2Addr> addrList = userMapper.getAddrListByUserId(101L, new Page<H2Addr>(0, 3));
         Assert.assertEquals(3, addrList.size());
     }
 
 
-
 }

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserAutoincrementTest.java

@@ -98,7 +98,7 @@ public class H2UserAutoincrementTest {
         user2.setAge(2);
         Assert.assertEquals(1, userMapper.insert(user2).intValue());
         Long userId2 = user2.getId();
-        Assert.assertEquals(id1.intValue()+1, userId2.intValue());
+        Assert.assertEquals(id1.intValue() + 1, userId2.intValue());
     }
 
 }

+ 11 - 11
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserDateVersionTest.java

@@ -87,7 +87,7 @@ public class H2UserDateVersionTest {
 
 
     @Test
-    public void testUpdateByIdNoDateVersion(){
+    public void testUpdateByIdNoDateVersion() {
         Long id = 991L;
         H2UserDateVersion user = new H2UserDateVersion();
         user.setId(id);
@@ -111,7 +111,7 @@ public class H2UserDateVersionTest {
 
 
     @Test
-    public void testUpdateByEntityWrapperNoDateVersion(){
+    public void testUpdateByEntityWrapperNoDateVersion() {
         Long id = 992L;
         H2UserDateVersion user = new H2UserDateVersion();
         user.setId(id);
@@ -135,7 +135,7 @@ public class H2UserDateVersionTest {
     }
 
     @Test
-    public void testUpdateByIdWithDateVersion(){
+    public void testUpdateByIdWithDateVersion() {
         Long id = 994L;
         H2UserDateVersion user = new H2UserDateVersion();
         user.setId(id);
@@ -146,16 +146,16 @@ public class H2UserDateVersionTest {
         user.setTestType(1);
         user.setVersion(1);
         Calendar cal = Calendar.getInstance();
-        cal.add(Calendar.DAY_OF_MONTH,-1);
+        cal.add(Calendar.DAY_OF_MONTH, -1);
         user.setTestDate(cal.getTime());
         userMapper.insertAllColumn(user);
 
-        System.out.println("before update: testDate="+user.getTestDate());
+        System.out.println("before update: testDate=" + user.getTestDate());
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
         H2UserDateVersion userDB = userMapper.selectById(id);
 
         Assert.assertNotNull(userDB.getTestDate());
-        String originalDateVersionStr =sdf.format(cal.getTime());
+        String originalDateVersionStr = sdf.format(cal.getTime());
         Assert.assertEquals(originalDateVersionStr, sdf.format(userDB.getTestDate()));
 
         userDB.setName("991");
@@ -163,7 +163,7 @@ public class H2UserDateVersionTest {
         userDB = userMapper.selectById(id);
         Assert.assertEquals("991", userDB.getName());
         Date versionDate = userDB.getTestDate();
-        System.out.println("after update: testDate="+versionDate);
+        System.out.println("after update: testDate=" + versionDate);
         String versionDateStr = sdf.format(versionDate);
         Assert.assertEquals(sdf.format(new Date()), versionDateStr);
 
@@ -172,7 +172,7 @@ public class H2UserDateVersionTest {
     }
 
     @Test
-    public void testUpdateByEntityWrapperWithDateVersion(){
+    public void testUpdateByEntityWrapperWithDateVersion() {
         Long id = 993L;
         H2UserDateVersion user = new H2UserDateVersion();
         user.setId(id);
@@ -183,7 +183,7 @@ public class H2UserDateVersionTest {
         user.setTestType(1);
         user.setVersion(1);
         Calendar cal = Calendar.getInstance();
-        cal.add(Calendar.DAY_OF_MONTH,-1);
+        cal.add(Calendar.DAY_OF_MONTH, -1);
         user.setTestDate(cal.getTime());
         userMapper.insertAllColumn(user);
 
@@ -194,14 +194,14 @@ public class H2UserDateVersionTest {
         userDB.setVersion(null);
         userMapper.update(updUser, new EntityWrapper<>(userDB));
 
-        System.out.println("before update: testDate="+userDB.getTestDate());
+        System.out.println("before update: testDate=" + userDB.getTestDate());
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
 
         userDB = userMapper.selectById(id);
         Assert.assertEquals("999", userDB.getName());
 
         Date versionDate = userDB.getTestDate();
-        System.out.println("after update: testDate="+versionDate);
+        System.out.println("after update: testDate=" + versionDate);
         String versionDateStr = sdf.format(versionDate);
         Assert.assertEquals(sdf.format(new Date()), versionDateStr);
     }

+ 19 - 18
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserNoOptLockTest.java

@@ -143,7 +143,7 @@ public class H2UserNoOptLockTest {
     }
 
     @Test
-    public void testUpdateByIdOptLock(){
+    public void testUpdateByIdOptLock() {
         Long id = 991L;
         H2User user = new H2User();
         user.setId(id);
@@ -167,7 +167,7 @@ public class H2UserNoOptLockTest {
     }
 
     @Test
-    public void testUpdateAllColumnByIdOptLock(){
+    public void testUpdateAllColumnByIdOptLock() {
         Long id = 997L;
         H2User user = new H2User();
         user.setId(id);
@@ -198,7 +198,7 @@ public class H2UserNoOptLockTest {
     }
 
     @Test
-    public void testUpdateByEntityWrapperOptLock(){
+    public void testUpdateByEntityWrapperOptLock() {
         Long id = 992L;
         H2User user = new H2User();
         user.setId(id);
@@ -224,7 +224,7 @@ public class H2UserNoOptLockTest {
     }
 
     @Test
-    public void testUpdateByEntityWrapperOptLockWithoutVersion(){
+    public void testUpdateByEntityWrapperOptLockWithoutVersion() {
         Long id = 993L;
         H2User user = new H2User();
         user.setId(id);
@@ -250,59 +250,60 @@ public class H2UserNoOptLockTest {
     }
 
     @Test
-    public void testUpdateBatch(){
+    public void testUpdateBatch() {
         List<H2User> list = userService.selectList(new EntityWrapper<H2User>());
         Map<Long, Integer> userVersionMap = new HashMap<>();
-        for(H2User u:list){
-            userVersionMap.put(u.getId(),u.getVersion());
+        for (H2User u : list) {
+            userVersionMap.put(u.getId(), u.getVersion());
         }
 
         Assert.assertTrue(userService.updateBatchById(list));
         list = userService.selectList(new EntityWrapper<H2User>());
-        for(H2User user:list){
+        for (H2User user : list) {
             Assert.assertEquals(userVersionMap.get(user.getId()).intValue(), user.getVersion().intValue());
         }
 
     }
 
     @Test
-    public void testUpdateInLoop(){
+    public void testUpdateInLoop() {
         List<H2User> list = userService.selectList(new EntityWrapper<H2User>());
-        Map<Long,Integer> versionBefore = new HashMap<>();
-        Map<Long,String> nameExpect = new HashMap<>();
+        Map<Long, Integer> versionBefore = new HashMap<>();
+        Map<Long, String> nameExpect = new HashMap<>();
         for (H2User h2User : list) {
             Long id = h2User.getId();
             Integer versionVal = h2User.getVersion();
             versionBefore.put(id, versionVal);
-            String randomName = h2User.getName()+"_"+new Random().nextInt(10);
+            String randomName = h2User.getName() + "_" + new Random().nextInt(10);
             nameExpect.put(id, randomName);
             h2User.setName(randomName);
             userService.updateById(h2User);
         }
 
         list = userService.selectList(new EntityWrapper<H2User>());
-        for(H2User u:list){
+        for (H2User u : list) {
             Assert.assertEquals(u.getName(), nameExpect.get(u.getId()));
             Assert.assertEquals(versionBefore.get(u.getId()).intValue(), u.getVersion().intValue());
         }
     }
+
     @Test
-    public void testUpdateAllColumnInLoop(){
+    public void testUpdateAllColumnInLoop() {
         List<H2User> list = userService.selectList(new EntityWrapper<H2User>());
-        Map<Long,Integer> versionBefore = new HashMap<>();
-        Map<Long,String> nameExpect = new HashMap<>();
+        Map<Long, Integer> versionBefore = new HashMap<>();
+        Map<Long, String> nameExpect = new HashMap<>();
         for (H2User h2User : list) {
             Long id = h2User.getId();
             Integer versionVal = h2User.getVersion();
             versionBefore.put(id, versionVal);
-            String randomName = h2User.getName()+"_"+new Random().nextInt(10);
+            String randomName = h2User.getName() + "_" + new Random().nextInt(10);
             nameExpect.put(id, randomName);
             h2User.setName(randomName);
             userService.updateAllColumnById(h2User);
         }
 
         list = userService.selectList(new EntityWrapper<H2User>());
-        for(H2User u:list){
+        for (H2User u : list) {
             Assert.assertEquals(u.getName(), nameExpect.get(u.getId()));
             Assert.assertEquals(versionBefore.get(u.getId()).intValue(), u.getVersion().intValue());
         }

+ 7 - 7
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserNoVersionTest.java

@@ -142,7 +142,7 @@ public class H2UserNoVersionTest {
     }
 
     @Test
-    public void testUpdateById(){
+    public void testUpdateById() {
         Long id = 991L;
         H2UserNoVersion user = new H2UserNoVersion();
         user.setId(id);
@@ -166,7 +166,7 @@ public class H2UserNoVersionTest {
     }
 
     @Test
-    public void testUpdateByEntityWrapper(){
+    public void testUpdateByEntityWrapper() {
         Long id = 992L;
         H2UserNoVersion user = new H2UserNoVersion();
         user.setId(id);
@@ -192,7 +192,7 @@ public class H2UserNoVersionTest {
     }
 
     @Test
-    public void testUpdateByEntityWrapper2(){
+    public void testUpdateByEntityWrapper2() {
         Long id = 993L;
         H2UserNoVersion user = new H2UserNoVersion();
         user.setId(id);
@@ -218,16 +218,16 @@ public class H2UserNoVersionTest {
     }
 
     @Test
-    public void testUpdateBatch(){
+    public void testUpdateBatch() {
         List<H2UserNoVersion> list = userService.selectList(new EntityWrapper<H2UserNoVersion>());
         Map<Long, Integer> userVersionMap = new HashMap<>();
-        for(H2UserNoVersion u:list){
-            userVersionMap.put(u.getId(),u.getVersion());
+        for (H2UserNoVersion u : list) {
+            userVersionMap.put(u.getId(), u.getVersion());
         }
         userService.updateBatchById(list);
 
         list = userService.selectList(new EntityWrapper<H2UserNoVersion>());
-        for(H2UserNoVersion user:list){
+        for (H2UserNoVersion user : list) {
             Assert.assertEquals(userVersionMap.get(user.getId()).intValue(), user.getVersion().intValue());
         }
     }

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/h2/H2UserTest.java

@@ -106,7 +106,7 @@ public class H2UserTest {
     public void testInsertBatch() {
         userService.insert(new H2User("sanmao", 1));
         List<H2User> h2Users = new ArrayList<>();
-        for (int i=0;i<10;i++) {
+        for (int i = 0; i < 10; i++) {
             H2User user = new H2User();
             user.setAge(1);
             user.setPrice(new BigDecimal("6" + i));
@@ -359,7 +359,7 @@ public class H2UserTest {
         for (H2User u : list) {
             Assert.assertEquals(u.getName(), nameExpect.get(u.getId()));
             if (u.getVersion() != null)
-            Assert.assertEquals(versionBefore.get(u.getId()) + 1, u.getVersion().intValue());
+                Assert.assertEquals(versionBefore.get(u.getId()) + 1, u.getVersion().intValue());
         }
     }
 

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/h2/entity/mapper/H2UserMapper.java

@@ -23,12 +23,12 @@ public interface H2UserMapper extends BaseMapper<H2User> {
             "select a.addr_id as addrId, a.addr_name as addrName from h2address a" +
                     " join h2user u on u.test_id=a.test_id and u.test_id=#{userId}"
     )
-     List<H2Addr> getAddrListByUserId(@Param("userId") Long userId);
+    List<H2Addr> getAddrListByUserId(@Param("userId") Long userId);
 
     @Select(
             "select a.addr_id as addrId, a.addr_name as addrName from h2address a" +
                     " join h2user u on u.test_id=a.test_id and u.test_id=#{userId}"
     )
-     List<H2Addr> getAddrListByUserId(@Param("userId") Long userId, Page<H2Addr> page);
+    List<H2Addr> getAddrListByUserId(@Param("userId") Long userId, Page<H2Addr> page);
 
 }

+ 5 - 5
src/test/java/com/baomidou/mybatisplus/test/mysql/LogicDeleteTest.java

@@ -64,11 +64,11 @@ public class LogicDeleteTest {
         System.err.println("第一次:逻辑删除testType 改为 1 成功记录数:" + rlt);
         rlt = userMapper.insert(new User(IdWorker.getId(), "logic-delete-2", 28, 2));
         System.err.println("再插入一条成功记录数:" + rlt);
-        rlt = userMapper.delete(Condition.create().eq("test_id",1111));
+        rlt = userMapper.delete(Condition.create().eq("test_id", 1111));
         System.err.println("全表逻辑删除成功记录数:" + rlt);
         List<User> userList = userMapper.selectList(null);
-        for (User u: userList) {
-            System.out.println("全表逻辑删除 ( id= " + u.getId() + " ) 展示结果"+u.getTestType());
+        for (User u : userList) {
+            System.out.println("全表逻辑删除 ( id= " + u.getId() + " ) 展示结果" + u.getTestType());
         }
 
         System.err.println("第二次:逻辑删除testType 改为 1 成功记录数:" + rlt);
@@ -77,8 +77,8 @@ public class LogicDeleteTest {
         rlt = userMapper.deleteByMap(map);
         System.err.println("全表逻辑删除 ByMap 成功记录数:" + rlt);
         userList = userMapper.selectList(null);
-        for (User u: userList) {
-            System.out.println("全表逻辑删除 ( id= " + u.getId() + " ) 展示结果"+u.getTestType());
+        for (User u : userList) {
+            System.out.println("全表逻辑删除 ( id= " + u.getId() + " ) 展示结果" + u.getTestType());
         }
     }
 }

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/mysql/MyMetaObjectHandler.java

@@ -46,8 +46,8 @@ public class MyMetaObjectHandler extends MetaObjectHandler {
 
         // 测试下划线
         Object testType = getFieldValByName("testType", metaObject);
-        System.out.println("testType="+testType);
-        if(testType==null){
+        System.out.println("testType=" + testType);
+        if (testType == null) {
             setFieldValByName("testType", 3, metaObject);
         }
     }

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/mysql/NoXMLTest.java

@@ -42,7 +42,7 @@ public class NoXMLTest {
 
     public static void main(String[] args) {
         /*
-		 * 加载配置文件
+         * 加载配置文件
 		 */
         InputStream in = NoXMLTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
         MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/mysql/SqlRunnerTest.java

@@ -42,7 +42,7 @@ public class SqlRunnerTest {
     @Test
     public void test1() {
         /*
-		 * 加载配置文件
+         * 加载配置文件
 		 */
         InputStream in = SqlRunnerTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
         MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/mysql/TransactionalTest.java

@@ -42,7 +42,7 @@ public class TransactionalTest {
      */
     public static void main(String[] args) {
         /*
-		 * 加载配置文件
+         * 加载配置文件
 		 */
         InputStream in = TransactionalTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
         MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

+ 10 - 9
src/test/java/com/baomidou/mybatisplus/test/mysql/UserMapperTest.java

@@ -15,6 +15,15 @@
  */
 package com.baomidou.mybatisplus.test.mysql;
 
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+
 import com.baomidou.mybatisplus.MybatisSessionFactoryBuilder;
 import com.baomidou.mybatisplus.entity.GlobalConfiguration;
 import com.baomidou.mybatisplus.mapper.EntityWrapper;
@@ -24,14 +33,6 @@ import com.baomidou.mybatisplus.test.mysql.entity.Role;
 import com.baomidou.mybatisplus.test.mysql.entity.User;
 import com.baomidou.mybatisplus.test.mysql.mapper.UserMapper;
 import com.baomidou.mybatisplus.toolkit.IdWorker;
-import org.apache.ibatis.session.SqlSession;
-import org.apache.ibatis.session.SqlSessionFactory;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 
 /**
  * <p>
@@ -72,7 +73,7 @@ public class UserMapperTest {
         MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
 
 		/*
-		 * 1、数据库字段驼峰命名不需要任何设置 2、当前演示是驼峰下划线混合命名 3、如下开启,表示数据库字段使用下划线命名,该设置是全局的。
+         * 1、数据库字段驼峰命名不需要任何设置 2、当前演示是驼峰下划线混合命名 3、如下开启,表示数据库字段使用下划线命名,该设置是全局的。
 		 * 开启该设置实体可无 @TableId(value = "test_id") 字段映射
 		 */
         // mf.setDbColumnUnderline(true);

+ 12 - 4
src/test/java/com/baomidou/mybatisplus/test/mysql/entity/Role.java

@@ -35,17 +35,25 @@ public class Role implements Serializable {
     @TableField(exist = false)
     private static final long serialVersionUID = 1L;
 
-    /** 主键 */
+    /**
+     * 主键
+     */
     @TableId
     private Long id;
 
-    /** 角色 */
+    /**
+     * 角色
+     */
     private String name;
 
-    /** 排序 */
+    /**
+     * 排序
+     */
     private Integer sort;
 
-    /** 描述 */
+    /**
+     * 描述
+     */
     private String description;
 
     public Long getId() {

+ 3 - 1
src/test/java/com/baomidou/mybatisplus/test/mysql/entity/Test.java

@@ -35,7 +35,9 @@ public class Test extends Model<Test> {
     // 静态属性会自动忽略
     private static final long serialVersionUID = 1L;
 
-    /** 主键 */
+    /**
+     * 主键
+     */
     // 默认会找 id 为主键,特殊命名需要注解 @TableId
     private Long id;
 

+ 1 - 2
src/test/java/com/baomidou/mybatisplus/test/mysql/mapper/UserMapper.java

@@ -37,8 +37,7 @@ public interface UserMapper extends MyBaseMapper<User> {
     /**
      * 用户列表,分页显示
      *
-     * @param pagination
-     *            传递参数包含该属性,即自动分页
+     * @param pagination 传递参数包含该属性,即自动分页
      * @return
      */
     List<User> selectListRow(RowBounds pagination);

+ 4 - 4
src/test/java/com/baomidou/mybatisplus/test/oracle/OracleUserTest.java

@@ -30,17 +30,17 @@ public class OracleUserTest {
     TestSequserMapper sequserMapper;
 
     @Test
-    public void testSelectListMp(){
+    public void testSelectListMp() {
         List<TestSequser> list = sequserMapper.selectList(new EntityWrapper<TestSequser>());
-        for(TestSequser u:list){
+        for (TestSequser u : list) {
             System.out.println(u);
         }
     }
 
     @Test
-    public void testSelectListNative(){
+    public void testSelectListNative() {
         List<TestSequser> list = sequserMapper.getList();
-        for(TestSequser u:list){
+        for (TestSequser u : list) {
             System.out.println(u);
         }
     }

+ 1 - 3
src/test/java/com/baomidou/mybatisplus/test/oracle/TestSequserMapperTest.java

@@ -42,9 +42,7 @@ public class TestSequserMapperTest {
 
 
     /**
-     *
      * Test Oracle Sequence
-     *
      */
     public static void main(String[] args) {
 
@@ -96,7 +94,7 @@ public class TestSequserMapperTest {
         for (TestSequser u : testList) {
             System.out.println(u);
         }
-        
+
         /**
          * 提交
          */

+ 1 - 3
src/test/java/com/baomidou/mybatisplus/test/oracle/TestUserMapperTest.java

@@ -41,9 +41,7 @@ public class TestUserMapperTest {
 
 
     /**
-     *
      * RUN 测试( 更多查看 MySql 测试类 )
-     *
      */
     public static void main(String[] args) {
 
@@ -62,7 +60,7 @@ public class TestUserMapperTest {
         mf.setGlobalConfig(gc);
 
 		/*
-		 * 1、数据库字段驼峰命名不需要任何设置
+         * 1、数据库字段驼峰命名不需要任何设置
 		 * 2、当前演示是驼峰下划线混合命名
 		 * 3、如下开启,表示数据库字段使用下划线命名,该设置是全局的。
 		 *	 开启该设置实体可无 @TableId(value = "test_id") 字段映射

+ 9 - 10
src/test/java/com/baomidou/mybatisplus/test/oracle/config/OracleDBConfig.java

@@ -15,27 +15,26 @@ import oracle.jdbc.OracleDriver;
 
 /**
  * 对应的数据库配置
- * 
- * @author yuxiaobin
  *
+ * @author yuxiaobin
  */
 @Configuration
 @EnableTransactionManagement
 public class OracleDBConfig {
 
-	@Bean
+    @Bean
     public DataSource dataSource() throws SQLException {
-		SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
-		dataSource.setDriver(new OracleDriver());
+        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
+        dataSource.setDriver(new OracleDriver());
         dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
         dataSource.setUsername("mp");
         dataSource.setPassword("mp");
         return dataSource;
     }
-	
-	@Bean
-	public DataSourceTransactionManager transactionManager(DataSource ds) {
-		return new DataSourceTransactionManager(ds);
-	}
+
+    @Bean
+    public DataSourceTransactionManager transactionManager(DataSource ds) {
+        return new DataSourceTransactionManager(ds);
+    }
 
 }

+ 9 - 9
src/test/java/com/baomidou/mybatisplus/test/oracle/entity/BaseTestEntity.java

@@ -25,14 +25,14 @@ public class BaseTestEntity implements Serializable {
     public BaseTestEntity() {
 
     }
-    
-    
-	public Long getId() {
-		return id;
-	}
-
-	public void setId(Long id) {
-		this.id = id;
-	}
+
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
 
 }

+ 51 - 52
src/test/java/com/baomidou/mybatisplus/test/oracle/entity/TestSequser.java

@@ -10,7 +10,7 @@ import com.baomidou.mybatisplus.annotations.TableName;
  */
 @TableName("TEST_SEQUSER")
 //@KeySequence("SEQ_TEST")
-public class TestSequser  extends BaseTestEntity implements Serializable{
+public class TestSequser extends BaseTestEntity implements Serializable {
 
     @TableField(exist = false)
     private static final long serialVersionUID = 1L;
@@ -18,21 +18,21 @@ public class TestSequser  extends BaseTestEntity implements Serializable{
     /**
      * 主键ID
      */
-   // @TableId(value = "ID")
-   // private Long id;
+    // @TableId(value = "ID")
+    // private Long id;
 
     /**
      * 名称
      */
-	@TableField(value = "NAME")
+    @TableField(value = "NAME")
     private String name;
 
     /**
      * 年龄
      */
-	@TableField(value = "age")
+    @TableField(value = "age")
     private Integer age;
-    
+
     /**
      * 测试下划线字段命名类型
      */
@@ -42,52 +42,51 @@ public class TestSequser  extends BaseTestEntity implements Serializable{
     public TestSequser() {
 
     }
-    
-    public TestSequser(String name,Integer age,Integer testType){
-    	this.name = name;
-    	this.age = age;
-    	this.testType = testType;
+
+    public TestSequser(String name, Integer age, Integer testType) {
+        this.name = name;
+        this.age = age;
+        this.testType = testType;
     }
 
-    
-	//public Long getId() {
-	//	return id;
-	//}
-
-	//public void setId(Long id) {
-	//	this.id = id;
-	//}
-
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public Integer getAge() {
-		return age;
-	}
-
-	public void setAge(Integer age) {
-		this.age = age;
-	}
-
-	public Integer getTestType() {
-		return testType;
-	}
-
-	public void setTestType(Integer testType) {
-		this.testType = testType;
-	}
-
-	@Override
-	public String toString() {
-		return "TestSequser{" +
-				"name='" + name + '\'' +
-				", age=" + age +
-				", testType=" + testType +
-				'}';
-	}
+    //public Long getId() {
+    //	return id;
+    //}
+
+    //public void setId(Long id) {
+    //	this.id = id;
+    //}
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Integer getAge() {
+        return age;
+    }
+
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+
+    public Integer getTestType() {
+        return testType;
+    }
+
+    public void setTestType(Integer testType) {
+        this.testType = testType;
+    }
+
+    @Override
+    public String toString() {
+        return "TestSequser{" +
+                "name='" + name + '\'' +
+                ", age=" + age +
+                ", testType=" + testType +
+                '}';
+    }
 }

+ 1 - 1
src/test/java/com/baomidou/mybatisplus/test/oracle/service/impl/OracleUserSeqServiceImpl.java

@@ -15,7 +15,7 @@ import com.baomidou.mybatisplus.test.oracle.service.OracleUserSeqService;
  * @date 2017/6/14
  */
 @Service
-public class OracleUserSeqServiceImpl extends ServiceImpl<TestSequserMapper, TestSequser> implements OracleUserSeqService{
+public class OracleUserSeqServiceImpl extends ServiceImpl<TestSequserMapper, TestSequser> implements OracleUserSeqService {
 
 
 }

+ 162 - 162
src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/OptimisticLockerInterceptorTest.java

@@ -31,168 +31,168 @@ import com.baomidou.mybatisplus.test.plugins.optimisticLocker.mapper.StringVersi
 import com.baomidou.mybatisplus.test.plugins.optimisticLocker.mapper.TimestampVersionUserMapper;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "/plugins/optimisticLockerInterceptor.xml" })
+@ContextConfiguration(locations = {"/plugins/optimisticLockerInterceptor.xml"})
 public class OptimisticLockerInterceptorTest {
 
-	@Autowired
-	private IntVersionUserMapper intVersionUserMapper;
-	@Autowired
-	private LongVersionUserMapper longVersionUserMapper;
-	@Autowired
-	private DateVersionUserMapper dateVersionUserMapper;
-	@Autowired
-	private TimestampVersionUserMapper timestampVersionUserMapper;
-	@Autowired
-	private StringVersionUserMapper stringersionUserMapper;
-	@Autowired
-	private LogicVersionUserMapper logicVersionUserMapper;
-	@Autowired
-	private SqlSessionTemplate sqlSessionTemplate;
-
-	@Before
-	public void setUp() throws Exception {
-		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();
-		Connection conn = session.getConnection();
-		Reader reader = Resources
-				.getResourceAsReader("h2/optlock/CreateDB.sql");
-		ScriptRunner runner = new ScriptRunner(conn);
-		runner.setLogWriter(null);
-		runner.runScript(reader);
-		reader.close();
-		session.close();
-	}
-
-	@Test
-	public void intVersionTest() {
-		// 查询数据
-		IntVersionUser versionUser = intVersionUserMapper.selectById(1);
-		Integer originVersion = versionUser.getVersion();
-		// 更新数据
-		versionUser.setName("苗神");
-		intVersionUserMapper.updateById(versionUser);
-		Assert.assertTrue(intVersionUserMapper.selectById(1).getVersion() == originVersion + 1);
-
-		// 重复测试一次,验证动态参数覆盖
-		// 查询数据
-		IntVersionUser versionUser2 = intVersionUserMapper.selectById(2);
-		Integer originVersion2 = versionUser2.getVersion();
-		versionUser2.setAge(16);
-		// 更新数据
-		versionUser2.setName("苗神");
-		intVersionUserMapper.updateById(versionUser2);
-		Assert.assertTrue(intVersionUserMapper.selectById(2).getVersion() == originVersion2 + 1);
-
-		// 测试一次数据库中version为null
-		IntVersionUser versionUser3 = intVersionUserMapper.selectById(3);
-		// 更新数据
-		versionUser3.setName("苗神");
-		intVersionUserMapper.updateById(versionUser3);
-		Assert.assertTrue(intVersionUserMapper.selectById(3).getVersion() == null);
-
-	}
-
-	@Test
-	public void longVersionTest() {
-		// 查询数据
-		LongVersionUser versionUser = longVersionUserMapper.selectById(1);
-		Long originVersion = versionUser.getVersion();
-		// 更新数据
-		versionUser.setName("苗神");
-		longVersionUserMapper.updateById(versionUser);
-		Assert.assertTrue(longVersionUserMapper.selectById(1).getVersion() == originVersion + 1);
-	}
-
-	@Test
-	public void dateVersionTest() {
-		// 插入数据
-		DateVersionUser versionUser = new DateVersionUser();
-		versionUser.setId(15L);
-		versionUser.setName("苗神");
-		Date originVersion = new Date();
-		versionUser.setVersion(originVersion);
-		dateVersionUserMapper.insert(versionUser);
-		// 更新数据
-		DateVersionUser q = dateVersionUserMapper.selectById(15);
-		q.setName("小锅盖");
-		dateVersionUserMapper.updateById(q);
-		Assert.assertTrue(dateVersionUserMapper.selectById(15L).getVersion().after(originVersion));
-	}
-
-	@Test
-	public void timestampVersionTest() {
-		// 插入数据
-		TimestampVersionUser versionUser = new TimestampVersionUser();
-		versionUser.setId(15L);
-		versionUser.setName("苗神");
-		Timestamp originVersion = new Timestamp(new Date().getTime());
-		versionUser.setVersion(originVersion);
-		timestampVersionUserMapper.insert(versionUser);
-		// 更新数据
-		TimestampVersionUser q = timestampVersionUserMapper.selectById(15);
-		q.setName("小锅盖");
-		timestampVersionUserMapper.updateById(q);
-		Assert.assertTrue(timestampVersionUserMapper.selectById(15L).getVersion().after(originVersion));
-	}
-
-	@Test
-	public void multiThreadVersionTest() {
-		final Random random = new Random();
-		for (int i = 50; i < 150; i++) {
-			new Thread(new Runnable() {
-				public void run() {
-					IntVersionUser intVersionUser = new IntVersionUser();
-					long id = random.nextLong();
-					intVersionUser.setId(id);
-					int version = random.nextInt();
-					intVersionUser.setName("改前" + version);
-					intVersionUser.setVersion(version);
-					intVersionUserMapper.insert(intVersionUser);
-					intVersionUser.setName("改后" + version);
-					intVersionUserMapper.updateById(intVersionUser);
-					Assert.assertTrue(intVersionUserMapper.selectById(id).getVersion() == version + 1);
-				}
-			}, "编号" + i).start();
-		}
-
-		try {
-			Thread.sleep(4000);
-		} catch (InterruptedException e) {
-			e.printStackTrace();
-		}
-	}
-
-	@Test
-	public void multiParamVersionTest() {
-		// 查询数据
-		Long id = 2L;
-		IntVersionUser versionUser = intVersionUserMapper.selectById(id);
-		Integer originVersion = versionUser.getVersion();
-		// null条件
-		versionUser.setVersion(null);
-		intVersionUserMapper.update(versionUser, null);
-		versionUser = intVersionUserMapper.selectById(id);
-		Assert.assertEquals(originVersion.intValue(), versionUser.getVersion().intValue());
-		// 空条件
-		versionUser.setVersion(null);
-		intVersionUserMapper.update(versionUser, new EntityWrapper<IntVersionUser>());
-		Assert.assertEquals(intVersionUserMapper.selectById(id).getVersion(), originVersion);
-		// 正常查询不带version
-		IntVersionUser wrapper = new IntVersionUser();
-		wrapper.setName("lisi");
-		intVersionUserMapper.update(versionUser, new EntityWrapper<>(wrapper));
-		versionUser = intVersionUserMapper.selectById(id);
-		Assert.assertEquals(versionUser.getVersion(), originVersion);
-		// 原始条件带version按原始逻辑走
-		IntVersionUser wrapper2 = new IntVersionUser();
-		wrapper2.setName("lisi");
-		wrapper2.setId(id);
-		wrapper2.setVersion(versionUser.getVersion() + 1);
-		int effRow = intVersionUserMapper.update(versionUser, new EntityWrapper<>(wrapper2));
-		Assert.assertEquals(0, effRow);
-	}
-
-	@Test // FIXME这个测试应该归属逻辑删除里
-	public void runWithDeleteLogicTest() {
-		logicVersionUserMapper.deleteById(1L);
-	}
+    @Autowired
+    private IntVersionUserMapper intVersionUserMapper;
+    @Autowired
+    private LongVersionUserMapper longVersionUserMapper;
+    @Autowired
+    private DateVersionUserMapper dateVersionUserMapper;
+    @Autowired
+    private TimestampVersionUserMapper timestampVersionUserMapper;
+    @Autowired
+    private StringVersionUserMapper stringersionUserMapper;
+    @Autowired
+    private LogicVersionUserMapper logicVersionUserMapper;
+    @Autowired
+    private SqlSessionTemplate sqlSessionTemplate;
+
+    @Before
+    public void setUp() throws Exception {
+        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();
+        Connection conn = session.getConnection();
+        Reader reader = Resources
+                .getResourceAsReader("h2/optlock/CreateDB.sql");
+        ScriptRunner runner = new ScriptRunner(conn);
+        runner.setLogWriter(null);
+        runner.runScript(reader);
+        reader.close();
+        session.close();
+    }
+
+    @Test
+    public void intVersionTest() {
+        // 查询数据
+        IntVersionUser versionUser = intVersionUserMapper.selectById(1);
+        Integer originVersion = versionUser.getVersion();
+        // 更新数据
+        versionUser.setName("苗神");
+        intVersionUserMapper.updateById(versionUser);
+        Assert.assertTrue(intVersionUserMapper.selectById(1).getVersion() == originVersion + 1);
+
+        // 重复测试一次,验证动态参数覆盖
+        // 查询数据
+        IntVersionUser versionUser2 = intVersionUserMapper.selectById(2);
+        Integer originVersion2 = versionUser2.getVersion();
+        versionUser2.setAge(16);
+        // 更新数据
+        versionUser2.setName("苗神");
+        intVersionUserMapper.updateById(versionUser2);
+        Assert.assertTrue(intVersionUserMapper.selectById(2).getVersion() == originVersion2 + 1);
+
+        // 测试一次数据库中version为null
+        IntVersionUser versionUser3 = intVersionUserMapper.selectById(3);
+        // 更新数据
+        versionUser3.setName("苗神");
+        intVersionUserMapper.updateById(versionUser3);
+        Assert.assertTrue(intVersionUserMapper.selectById(3).getVersion() == null);
+
+    }
+
+    @Test
+    public void longVersionTest() {
+        // 查询数据
+        LongVersionUser versionUser = longVersionUserMapper.selectById(1);
+        Long originVersion = versionUser.getVersion();
+        // 更新数据
+        versionUser.setName("苗神");
+        longVersionUserMapper.updateById(versionUser);
+        Assert.assertTrue(longVersionUserMapper.selectById(1).getVersion() == originVersion + 1);
+    }
+
+    @Test
+    public void dateVersionTest() {
+        // 插入数据
+        DateVersionUser versionUser = new DateVersionUser();
+        versionUser.setId(15L);
+        versionUser.setName("苗神");
+        Date originVersion = new Date();
+        versionUser.setVersion(originVersion);
+        dateVersionUserMapper.insert(versionUser);
+        // 更新数据
+        DateVersionUser q = dateVersionUserMapper.selectById(15);
+        q.setName("小锅盖");
+        dateVersionUserMapper.updateById(q);
+        Assert.assertTrue(dateVersionUserMapper.selectById(15L).getVersion().after(originVersion));
+    }
+
+    @Test
+    public void timestampVersionTest() {
+        // 插入数据
+        TimestampVersionUser versionUser = new TimestampVersionUser();
+        versionUser.setId(15L);
+        versionUser.setName("苗神");
+        Timestamp originVersion = new Timestamp(new Date().getTime());
+        versionUser.setVersion(originVersion);
+        timestampVersionUserMapper.insert(versionUser);
+        // 更新数据
+        TimestampVersionUser q = timestampVersionUserMapper.selectById(15);
+        q.setName("小锅盖");
+        timestampVersionUserMapper.updateById(q);
+        Assert.assertTrue(timestampVersionUserMapper.selectById(15L).getVersion().after(originVersion));
+    }
+
+    @Test
+    public void multiThreadVersionTest() {
+        final Random random = new Random();
+        for (int i = 50; i < 150; i++) {
+            new Thread(new Runnable() {
+                public void run() {
+                    IntVersionUser intVersionUser = new IntVersionUser();
+                    long id = random.nextLong();
+                    intVersionUser.setId(id);
+                    int version = random.nextInt();
+                    intVersionUser.setName("改前" + version);
+                    intVersionUser.setVersion(version);
+                    intVersionUserMapper.insert(intVersionUser);
+                    intVersionUser.setName("改后" + version);
+                    intVersionUserMapper.updateById(intVersionUser);
+                    Assert.assertTrue(intVersionUserMapper.selectById(id).getVersion() == version + 1);
+                }
+            }, "编号" + i).start();
+        }
+
+        try {
+            Thread.sleep(4000);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void multiParamVersionTest() {
+        // 查询数据
+        Long id = 2L;
+        IntVersionUser versionUser = intVersionUserMapper.selectById(id);
+        Integer originVersion = versionUser.getVersion();
+        // null条件
+        versionUser.setVersion(null);
+        intVersionUserMapper.update(versionUser, null);
+        versionUser = intVersionUserMapper.selectById(id);
+        Assert.assertEquals(originVersion.intValue(), versionUser.getVersion().intValue());
+        // 空条件
+        versionUser.setVersion(null);
+        intVersionUserMapper.update(versionUser, new EntityWrapper<IntVersionUser>());
+        Assert.assertEquals(intVersionUserMapper.selectById(id).getVersion(), originVersion);
+        // 正常查询不带version
+        IntVersionUser wrapper = new IntVersionUser();
+        wrapper.setName("lisi");
+        intVersionUserMapper.update(versionUser, new EntityWrapper<>(wrapper));
+        versionUser = intVersionUserMapper.selectById(id);
+        Assert.assertEquals(versionUser.getVersion(), originVersion);
+        // 原始条件带version按原始逻辑走
+        IntVersionUser wrapper2 = new IntVersionUser();
+        wrapper2.setName("lisi");
+        wrapper2.setId(id);
+        wrapper2.setVersion(versionUser.getVersion() + 1);
+        int effRow = intVersionUserMapper.update(versionUser, new EntityWrapper<>(wrapper2));
+        Assert.assertEquals(0, effRow);
+    }
+
+    @Test // FIXME这个测试应该归属逻辑删除里
+    public void runWithDeleteLogicTest() {
+        logicVersionUserMapper.deleteById(1L);
+    }
 }

+ 1 - 0
src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/IntVersionFather.java

@@ -3,6 +3,7 @@ package com.baomidou.mybatisplus.test.plugins.optimisticLocker.entity;
 import com.baomidou.mybatisplus.annotations.Version;
 
 public class IntVersionFather {
+
     @Version
     private Integer version;
 

+ 23 - 23
src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/IntVersionUser.java

@@ -8,37 +8,37 @@ import com.baomidou.mybatisplus.annotations.TableName;
 @TableName("version_user")
 public class IntVersionUser extends IntVersionFather implements Serializable {
 
-	@TableField(exist = false)
-	private static final long serialVersionUID = 1L;
+    @TableField(exist = false)
+    private static final long serialVersionUID = 1L;
 
-	private Long id;
+    private Long id;
 
-	private String name;
+    private String name;
 
-	private Integer age;
+    private Integer age;
 
-	public Long getId() {
-		return id;
-	}
+    public Long getId() {
+        return id;
+    }
 
-	public void setId(Long id) {
-		this.id = id;
-	}
+    public void setId(Long id) {
+        this.id = id;
+    }
 
-	public String getName() {
-		return name;
-	}
+    public String getName() {
+        return name;
+    }
 
-	public void setName(String name) {
-		this.name = name;
-	}
+    public void setName(String name) {
+        this.name = name;
+    }
 
-	public Integer getAge() {
-		return age;
-	}
+    public Integer getAge() {
+        return age;
+    }
 
-	public void setAge(Integer age) {
-		this.age = age;
-	}
+    public void setAge(Integer age) {
+        this.age = age;
+    }
 
 }

+ 33 - 33
src/test/java/com/baomidou/mybatisplus/test/plugins/optimisticLocker/entity/LogicVersionUser.java

@@ -10,49 +10,49 @@ import com.baomidou.mybatisplus.annotations.Version;
 @TableName("version_user")
 public class LogicVersionUser implements Serializable {
 
-	@TableField(exist = false)
-	private static final long serialVersionUID = 1L;
+    @TableField(exist = false)
+    private static final long serialVersionUID = 1L;
 
-	private Long id;
+    private Long id;
 
-	private String name;
+    private String name;
 
-	@Version
-	private Short version;
-	
-	@TableLogic(value = "0", delval = "1")
-	private Integer isDelete;
+    @Version
+    private Short version;
 
-	public Long getId() {
-		return id;
-	}
+    @TableLogic(value = "0", delval = "1")
+    private Integer isDelete;
 
-	public void setId(Long id) {
-		this.id = id;
-	}
+    public Long getId() {
+        return id;
+    }
 
-	public String getName() {
-		return name;
-	}
+    public void setId(Long id) {
+        this.id = id;
+    }
 
-	public void setName(String name) {
-		this.name = name;
-	}
+    public String getName() {
+        return name;
+    }
 
-	public Short getVersion() {
-		return version;
-	}
+    public void setName(String name) {
+        this.name = name;
+    }
 
-	public void setVersion(Short version) {
-		this.version = version;
-	}
+    public Short getVersion() {
+        return version;
+    }
 
-	public Integer getIsDelete() {
-		return isDelete;
-	}
+    public void setVersion(Short version) {
+        this.version = version;
+    }
 
-	public void setIsDelete(Integer isDelete) {
-		this.isDelete = isDelete;
-	}
+    public Integer getIsDelete() {
+        return isDelete;
+    }
+
+    public void setIsDelete(Integer isDelete) {
+        this.isDelete = isDelete;
+    }
 
 }

+ 66 - 65
src/test/java/com/baomidou/mybatisplus/test/plugins/paginationInterceptor/PaginationInterceptorTest.java

@@ -24,77 +24,78 @@ import com.baomidou.mybatisplus.test.plugins.paginationInterceptor.mapper.PageUs
 import com.baomidou.mybatisplus.test.plugins.paginationInterceptor.service.PageUserService;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "/plugins/paginationInterceptor.xml" })
+@ContextConfiguration(locations = {"/plugins/paginationInterceptor.xml"})
 public class PaginationInterceptorTest {
-	@Autowired
-	private SqlSessionTemplate sqlSessionTemplate;
-	@Autowired
-	private PageUserService pageUserService;
-	@Autowired
-	private PageUserMapper pageUserMapper;
 
-	private int current;
-	private int size;
+    @Autowired
+    private SqlSessionTemplate sqlSessionTemplate;
+    @Autowired
+    private PageUserService pageUserService;
+    @Autowired
+    private PageUserMapper pageUserMapper;
 
-	@Before
-	public void setUp() throws Exception {
-		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();
-		Connection conn = session.getConnection();
-		Reader reader = Resources.getResourceAsReader("com/baomidou/mybatisplus/test/plugins/paginationInterceptor/CreateDB.sql");
-		ScriptRunner runner = new ScriptRunner(conn);
-		runner.setLogWriter(null);
-		runner.runScript(reader);
-		reader.close();
-		session.close();
-		// 随机当前页和分页大小
-		size = RandomUtils.nextInt(1, 50);
-		current = RandomUtils.nextInt(1, 200 / size);
-		System.err.println("当前页为:" + current + " 分页大小为" + size);
-	}
+    private int current;
+    private int size;
 
-	@Test
-	public void pageSimpleTest() {
-		// 最基础分页
-		Page<PageUser> page1 = new Page<>(current, size);
-		Page<PageUser> result1 = pageUserService.selectPage(page1);
-		Assert.assertTrue(!result1.getRecords().isEmpty());
+    @Before
+    public void setUp() throws Exception {
+        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();
+        Connection conn = session.getConnection();
+        Reader reader = Resources.getResourceAsReader("com/baomidou/mybatisplus/test/plugins/paginationInterceptor/CreateDB.sql");
+        ScriptRunner runner = new ScriptRunner(conn);
+        runner.setLogWriter(null);
+        runner.runScript(reader);
+        reader.close();
+        session.close();
+        // 随机当前页和分页大小
+        size = RandomUtils.nextInt(1, 50);
+        current = RandomUtils.nextInt(1, 200 / size);
+        System.err.println("当前页为:" + current + " 分页大小为" + size);
+    }
 
-	}
+    @Test
+    public void pageSimpleTest() {
+        // 最基础分页
+        Page<PageUser> page1 = new Page<>(current, size);
+        Page<PageUser> result1 = pageUserService.selectPage(page1);
+        Assert.assertTrue(!result1.getRecords().isEmpty());
 
-	@Test
-	public void pageOrderByTest() {
-		// 带OrderBy
-		Page<PageUser> page2 = new Page<>(current, size, "name");
-		Page<PageUser> result2 = pageUserService.selectPage(page2);
-		Assert.assertTrue(!result2.getRecords().isEmpty());
-		// 没有orderby但是设置了倒叙
-		Page<PageUser> page3 = new Page<>(current, size);
-		page3.setAsc(false);
-		Page<PageUser> result3 = pageUserService.selectPage(page3);
-		Assert.assertTrue(!result3.getRecords().isEmpty());
-		// 有orderby设置了倒叙
-		Page<PageUser> page4 = new Page<>(current, size, "name");
-		page3.setAsc(false);
-		Page<PageUser> result4 = pageUserService.selectPage(page4);
-		Assert.assertTrue(!result4.getRecords().isEmpty());
-	}
+    }
 
-	@Test
-	public void pageCountTest() {
-		// 设置不count
-		Page<PageUser> page = new Page<>(current, size);
-		page.setSearchCount(false);
-		Page<PageUser> result = pageUserService.selectPage(page);
-		Assert.assertTrue(result.getTotal() == 0);
-	}
+    @Test
+    public void pageOrderByTest() {
+        // 带OrderBy
+        Page<PageUser> page2 = new Page<>(current, size, "name");
+        Page<PageUser> result2 = pageUserService.selectPage(page2);
+        Assert.assertTrue(!result2.getRecords().isEmpty());
+        // 没有orderby但是设置了倒叙
+        Page<PageUser> page3 = new Page<>(current, size);
+        page3.setAsc(false);
+        Page<PageUser> result3 = pageUserService.selectPage(page3);
+        Assert.assertTrue(!result3.getRecords().isEmpty());
+        // 有orderby设置了倒叙
+        Page<PageUser> page4 = new Page<>(current, size, "name");
+        page3.setAsc(false);
+        Page<PageUser> result4 = pageUserService.selectPage(page4);
+        Assert.assertTrue(!result4.getRecords().isEmpty());
+    }
 
-	@Test
-	public void rowBoundTest() {
-		System.err.println("测试原生RowBounds分页");
-		int offset = RandomUtils.nextInt(1, 190);
-		int limit = RandomUtils.nextInt(1,20);
-		RowBounds rowBounds = new RowBounds(offset, limit);
-		List<PageUser> result = pageUserMapper.selectPage(rowBounds, null);
-		Assert.assertTrue(!result.isEmpty());
-	}
+    @Test
+    public void pageCountTest() {
+        // 设置不count
+        Page<PageUser> page = new Page<>(current, size);
+        page.setSearchCount(false);
+        Page<PageUser> result = pageUserService.selectPage(page);
+        Assert.assertTrue(result.getTotal() == 0);
+    }
+
+    @Test
+    public void rowBoundTest() {
+        System.err.println("测试原生RowBounds分页");
+        int offset = RandomUtils.nextInt(1, 190);
+        int limit = RandomUtils.nextInt(1, 20);
+        RowBounds rowBounds = new RowBounds(offset, limit);
+        List<PageUser> result = pageUserMapper.selectPage(rowBounds, null);
+        Assert.assertTrue(!result.isEmpty());
+    }
 }

+ 28 - 28
src/test/java/com/baomidou/mybatisplus/test/plugins/paginationInterceptor/entity/PageUser.java

@@ -7,33 +7,33 @@ import com.baomidou.mybatisplus.annotations.TableName;
 @TableName("page_user")
 public class PageUser implements Serializable {
 
-	private static final long serialVersionUID = 1L;
-	private Integer id;
-	private String name;
-	private Short age;
-
-	public Integer getId() {
-		return id;
-	}
-
-	public void setId(Integer id) {
-		this.id = id;
-	}
-
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public Short getAge() {
-		return age;
-	}
-
-	public void setAge(Short age) {
-		this.age = age;
-	}
+    private static final long serialVersionUID = 1L;
+    private Integer id;
+    private String name;
+    private Short age;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Short getAge() {
+        return age;
+    }
+
+    public void setAge(Short age) {
+        this.age = age;
+    }
 
 }