Selaa lähdekoodia

update: sharding支持SimpleExecutor,新增对beforePrepare拦截

zengzhihong 4 vuotta sitten
vanhempi
commit
4f1346cd01

+ 17 - 2
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/handler/sharding/ShardingNode.java

@@ -1,11 +1,26 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.handler.sharding;
 
+import java.util.List;
+
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.Setter;
 
-import java.util.List;
-
 /**
  * @author zengzhihong
  * @since 2021-01-14

+ 51 - 12
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/handler/sharding/ShardingNodeExtractor.java

@@ -1,12 +1,54 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.handler.sharding;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
+
 import lombok.Getter;
-import net.sf.jsqlparser.expression.*;
-import net.sf.jsqlparser.expression.operators.arithmetic.*;
+import net.sf.jsqlparser.expression.AllComparisonExpression;
+import net.sf.jsqlparser.expression.AnyComparisonExpression;
+import net.sf.jsqlparser.expression.CastExpression;
+import net.sf.jsqlparser.expression.Expression;
+import net.sf.jsqlparser.expression.JdbcNamedParameter;
+import net.sf.jsqlparser.expression.JdbcParameter;
+import net.sf.jsqlparser.expression.Parenthesis;
+import net.sf.jsqlparser.expression.operators.arithmetic.Addition;
+import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd;
+import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr;
+import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor;
+import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
+import net.sf.jsqlparser.expression.operators.arithmetic.Division;
+import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction;
 import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
 import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
-import net.sf.jsqlparser.expression.operators.relational.*;
+import net.sf.jsqlparser.expression.operators.relational.Between;
+import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
+import net.sf.jsqlparser.expression.operators.relational.ExistsExpression;
+import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
+import net.sf.jsqlparser.expression.operators.relational.GreaterThan;
+import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals;
+import net.sf.jsqlparser.expression.operators.relational.InExpression;
+import net.sf.jsqlparser.expression.operators.relational.LikeExpression;
+import net.sf.jsqlparser.expression.operators.relational.Matches;
+import net.sf.jsqlparser.expression.operators.relational.MinorThan;
+import net.sf.jsqlparser.expression.operators.relational.MinorThanEquals;
+import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo;
 import net.sf.jsqlparser.schema.Column;
 import net.sf.jsqlparser.schema.Table;
 import net.sf.jsqlparser.statement.Statement;
@@ -18,9 +60,6 @@ import net.sf.jsqlparser.statement.select.SubSelect;
 import net.sf.jsqlparser.statement.update.Update;
 import net.sf.jsqlparser.util.TablesNamesFinder;
 
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * @author zengzhihong
  * @since 2021-01-14
@@ -48,13 +87,13 @@ public class ShardingNodeExtractor extends TablesNamesFinder {
     public void visit(Column column) {
         this.currentColumn = column;
         final ShardingNode<Table, ShardingNode<String, Integer>> tableNode =
-            obtainTableNode(column);
+                obtainTableNode(column);
         // SQL正确的前提下 tableNode一定不为null
         if (null == tableNode) {
             throw ExceptionUtils.mpe("please determine the alias on sql");
         }
         final ShardingNode<String, Integer> columnNode =
-            tableNode.getList().stream().filter(i -> i.getNode().equals(column.getColumnName())).findFirst().orElse(null);
+                tableNode.getList().stream().filter(i -> i.getNode().equals(column.getColumnName())).findFirst().orElse(null);
         if (null == columnNode) {
             tableNode.getList().add(new ShardingNode<>(column.getColumnName(), new ArrayList<>()));
         }
@@ -72,7 +111,7 @@ public class ShardingNodeExtractor extends TablesNamesFinder {
                         continue;
                     }
                     visit(insert.getColumns().get(i));
-                    visit((JdbcParameter)expression);
+                    visit((JdbcParameter) expression);
                 }
             }
         }
@@ -113,12 +152,12 @@ public class ShardingNodeExtractor extends TablesNamesFinder {
     @Override
     public void visit(JdbcParameter jdbcParameter) {
         final ShardingNode<Table, ShardingNode<String, Integer>> tableNode =
-            obtainTableNode(this.currentColumn);
+                obtainTableNode(this.currentColumn);
         if (null == tableNode) {
             throw ExceptionUtils.mpe("please determine the alias on sql");
         }
         final ShardingNode<String, Integer> columnNode =
-            tableNode.getList().stream().filter(i -> i.getNode().equals(this.currentColumn.getColumnName())).findFirst().orElse(null);
+                tableNode.getList().stream().filter(i -> i.getNode().equals(this.currentColumn.getColumnName())).findFirst().orElse(null);
         if (null == columnNode) {
             throw ExceptionUtils.mpe("please determine the alias on sql");
         }
@@ -134,7 +173,7 @@ public class ShardingNodeExtractor extends TablesNamesFinder {
 
     private ShardingNode<Table, ShardingNode<String, Integer>> obtainTableNode(Column column) {
         return null == column || null == column.getTable() || null == column.getTable().getName() ? nodes.get(0) :
-            nodes.stream().filter(i -> i.getNode().getAlias().getName().equals(column.getTable().getName())).findFirst().orElse(null);
+                nodes.stream().filter(i -> i.getNode().getAlias().getName().equals(column.getTable().getName())).findFirst().orElse(null);
     }
 
 

+ 15 - 0
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/handler/sharding/ShardingProcessor.java

@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.handler.sharding;
 
 import java.util.List;

+ 15 - 0
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/handler/sharding/ShardingRuleEnum.java

@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.handler.sharding;
 
 /**

+ 19 - 3
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/handler/sharding/ShardingStrategy.java

@@ -1,13 +1,29 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.handler.sharding;
 
+import java.util.Arrays;
+import java.util.List;
+
 import com.baomidou.mybatisplus.core.toolkit.StringPool;
+
 import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.Setter;
 
-import java.util.Arrays;
-import java.util.List;
-
 /**
  * @author zengzhihong
  * @since 2021-01-14

+ 53 - 14
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/inner/ShardingInnerInterceptor.java

@@ -1,5 +1,36 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.extension.plugins.inner;
 
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.ibatis.executor.BatchExecutor;
+import org.apache.ibatis.executor.Executor;
+import org.apache.ibatis.executor.ReuseExecutor;
+import org.apache.ibatis.executor.statement.StatementHandler;
+import org.apache.ibatis.mapping.ParameterMapping;
+import org.apache.ibatis.mapping.ParameterMode;
+import org.apache.ibatis.reflection.MetaObject;
+
 import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
 import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
@@ -10,6 +41,7 @@ import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingNode;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingNodeExtractor;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingProcessor;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingStrategy;
+
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 import net.sf.jsqlparser.schema.Table;
@@ -18,13 +50,6 @@ import net.sf.jsqlparser.statement.delete.Delete;
 import net.sf.jsqlparser.statement.insert.Insert;
 import net.sf.jsqlparser.statement.select.Select;
 import net.sf.jsqlparser.statement.update.Update;
-import org.apache.ibatis.executor.statement.StatementHandler;
-import org.apache.ibatis.mapping.ParameterMapping;
-import org.apache.ibatis.mapping.ParameterMode;
-import org.apache.ibatis.reflection.MetaObject;
-
-import java.util.*;
-import java.util.stream.Collectors;
 
 /**
  * @author zengzhihong
@@ -38,17 +63,22 @@ public class ShardingInnerInterceptor extends JsqlParserSupport implements Inner
         shardingMap = Arrays.stream(shardingStrategies).collect(Collectors.toMap(ShardingStrategy::getLogicTable, i -> new ShardingStrategyProcessor(i, ClassUtils.newInstance(i.getProcessor()))));
     }
 
-    @AllArgsConstructor
-    @Getter
-    static class ShardingStrategyProcessor {
-
-        private final ShardingStrategy strategy;
-        private final ShardingProcessor processor;
+    @Override
+    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
+        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
+        final Executor executor = mpSh.executor();
+        if (executor instanceof BatchExecutor || executor instanceof ReuseExecutor) {
+            return;
+        }
+        doParse(mpSh);
     }
 
     @Override
     public void beforeGetBoundSql(StatementHandler sh) {
-        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
+        doParse(PluginUtils.mpStatementHandler(sh));
+    }
+
+    private void doParse(PluginUtils.MPStatementHandler mpSh) {
         if (InterceptorIgnoreHelper.willIgnoreSharding(mpSh.mappedStatement().getId())) {
             return;
         }
@@ -128,4 +158,13 @@ public class ShardingInnerInterceptor extends JsqlParserSupport implements Inner
         }
         return values;
     }
+
+    @AllArgsConstructor
+    @Getter
+    static class ShardingStrategyProcessor {
+
+        private final ShardingStrategy strategy;
+
+        private final ShardingProcessor processor;
+    }
 }

+ 18 - 2
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/sharding/ShardingOrder.java

@@ -1,11 +1,27 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.test.sharding;
 
+import java.time.LocalDateTime;
+
 import com.baomidou.mybatisplus.annotation.TableId;
+
 import lombok.Data;
 import lombok.experimental.Accessors;
 
-import java.time.LocalDateTime;
-
 /**
  * @author miemie
  * @since 2020-06-24

+ 17 - 1
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/sharding/ShardingOrderMapper.java

@@ -1,8 +1,24 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.test.sharding;
 
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import org.apache.ibatis.annotations.Param;
 
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+
 /**
  * @author zengzhihong
  */

+ 48 - 31
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/sharding/ShardingTest.java

@@ -1,22 +1,39 @@
+/*
+ * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
+ *
+ * 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
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
 package com.baomidou.mybatisplus.test.sharding;
 
+import java.time.LocalDateTime;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.ibatis.plugin.Interceptor;
+import org.assertj.core.util.Lists;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
 import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingProcessor;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingRuleEnum;
 import com.baomidou.mybatisplus.extension.plugins.handler.sharding.ShardingStrategy;
 import com.baomidou.mybatisplus.extension.plugins.inner.ShardingInnerInterceptor;
 import com.baomidou.mybatisplus.test.BaseDbTest;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.ibatis.plugin.Interceptor;
-import org.assertj.core.util.Lists;
-import org.junit.jupiter.api.MethodOrderer;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestMethodOrder;
 
-import java.time.LocalDateTime;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
+import lombok.extern.slf4j.Slf4j;
 
 /**
  * @author zengzhihong
@@ -118,7 +135,7 @@ public class ShardingTest extends BaseDbTest<ShardingOrderMapper> {
     protected List<Interceptor> interceptors() {
         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
         final ShardingStrategy orderShardingHashStrategy = new ShardingStrategy("sharding_order",
-            "order_id", ShardingRuleEnum.ABSOLUTE, OrderShardingProcessor.class);
+                "order_id", ShardingRuleEnum.ABSOLUTE, OrderShardingProcessor.class);
         interceptor.addInnerInterceptor(new ShardingInnerInterceptor(orderShardingHashStrategy));
         return Collections.singletonList(interceptor);
     }
@@ -126,26 +143,26 @@ public class ShardingTest extends BaseDbTest<ShardingOrderMapper> {
     @Override
     protected List<String> tableSql() {
         return Lists.newArrayList("CREATE TABLE IF NOT EXISTS sharding_order_01\n" +
-                "            (\n" +
-                "                order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
-                "                subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
-                "                create_time  DATETIME      NULL,\n" +
-                "                PRIMARY KEY (order_id)\n" +
-                "            )",
-            "CREATE TABLE IF NOT EXISTS sharding_order_02\n" +
-                "        (\n" +
-                "            order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
-                "            subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
-                "            create_time  DATETIME      NULL,\n" +
-                "        PRIMARY KEY (order_id)\n" +
-                ")",
-            "CREATE TABLE IF NOT EXISTS sharding_order_03\n" +
-                "        (\n" +
-                "            order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
-                "            subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
-                "            create_time  DATETIME      NULL,\n" +
-                "        PRIMARY KEY (order_id)\n" +
-                ")");
+                        "            (\n" +
+                        "                order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
+                        "                subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
+                        "                create_time  DATETIME      NULL,\n" +
+                        "                PRIMARY KEY (order_id)\n" +
+                        "            )",
+                "CREATE TABLE IF NOT EXISTS sharding_order_02\n" +
+                        "        (\n" +
+                        "            order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
+                        "            subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
+                        "            create_time  DATETIME      NULL,\n" +
+                        "        PRIMARY KEY (order_id)\n" +
+                        ")",
+                "CREATE TABLE IF NOT EXISTS sharding_order_03\n" +
+                        "        (\n" +
+                        "            order_id     BIGINT(20)  NOT NULL AUTO_INCREMENT,\n" +
+                        "            subject   VARCHAR(30) NULL DEFAULT NULL,\n" +
+                        "            create_time  DATETIME      NULL,\n" +
+                        "        PRIMARY KEY (order_id)\n" +
+                        ")");
     }
 
     static class OrderShardingProcessor implements ShardingProcessor {