Pārlūkot izejas kodu

开发多租户支持

hubin 7 gadi atpakaļ
vecāks
revīzija
913847c5d4

+ 0 - 4
src/main/java/com/baomidou/mybatisplus/parser/package-info.java

@@ -1,4 +0,0 @@
-/**
- * SQL 解析相关类
- */
-package com.baomidou.mybatisplus.parser;

+ 2 - 2
src/main/java/com/baomidou/mybatisplus/plugins/CachePaginationInterceptor.java

@@ -33,8 +33,8 @@ import org.apache.ibatis.session.ResultHandler;
 import org.apache.ibatis.session.RowBounds;
 
 import com.baomidou.mybatisplus.enums.DBType;
-import com.baomidou.mybatisplus.parser.AbstractSqlParser;
-import com.baomidou.mybatisplus.parser.SqlInfo;
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
 import com.baomidou.mybatisplus.plugins.pagination.Pagination;
 import com.baomidou.mybatisplus.toolkit.JdbcUtils;

+ 15 - 7
src/main/java/com/baomidou/mybatisplus/plugins/PaginationInterceptor.java

@@ -38,11 +38,11 @@ import org.apache.ibatis.session.RowBounds;
 
 import com.baomidou.mybatisplus.MybatisDefaultParameterHandler;
 import com.baomidou.mybatisplus.enums.DBType;
-import com.baomidou.mybatisplus.parser.AbstractSqlParser;
-import com.baomidou.mybatisplus.parser.SqlInfo;
 import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
 import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
 import com.baomidou.mybatisplus.plugins.pagination.Pagination;
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 import com.baomidou.mybatisplus.toolkit.JdbcUtils;
 import com.baomidou.mybatisplus.toolkit.PluginUtils;
 import com.baomidou.mybatisplus.toolkit.SqlUtils;
@@ -75,6 +75,7 @@ public class PaginationInterceptor implements Interceptor {
     /**
      * Physical Pagination Interceptor for all the queries with parameter {@link org.apache.ibatis.session.RowBounds}
      */
+    @Override
     public Object intercept(Invocation invocation) throws Throwable {
         StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
         MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
@@ -163,6 +164,7 @@ public class PaginationInterceptor implements Interceptor {
         }
     }
 
+    @Override
     public Object plugin(Object target) {
         if (target instanceof StatementHandler) {
             return Plugin.wrap(target, this);
@@ -170,6 +172,7 @@ public class PaginationInterceptor implements Interceptor {
         return target;
     }
 
+    @Override
     public void setProperties(Properties prop) {
         String dialectType = prop.getProperty("dialectType");
         String dialectClazz = prop.getProperty("dialectClazz");
@@ -182,23 +185,28 @@ public class PaginationInterceptor implements Interceptor {
         }
     }
 
-    public void setDialectType(String dialectType) {
+    public PaginationInterceptor setDialectType(String dialectType) {
         this.dialectType = dialectType;
+        return this;
     }
 
-    public void setDialectClazz(String dialectClazz) {
+    public PaginationInterceptor setDialectClazz(String dialectClazz) {
         this.dialectClazz = dialectClazz;
+        return this;
     }
 
-    public void setOverflowCurrent(boolean overflowCurrent) {
+    public PaginationInterceptor setOverflowCurrent(boolean overflowCurrent) {
         this.overflowCurrent = overflowCurrent;
+        return this;
     }
 
-    public void setSqlParser(AbstractSqlParser sqlParser) {
+    public PaginationInterceptor setSqlParser(AbstractSqlParser sqlParser) {
         this.sqlParser = sqlParser;
+        return this;
     }
 
-    public void setLocalPage(boolean localPage) {
+    public PaginationInterceptor setLocalPage(boolean localPage) {
         this.localPage = localPage;
+        return this;
     }
 }

+ 96 - 0
src/main/java/com/baomidou/mybatisplus/plugins/SqlParserInterceptor.java

@@ -0,0 +1,96 @@
+/**
+ * Copyright (c) 2011-2020, 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.
+ */
+package com.baomidou.mybatisplus.plugins;
+
+import java.sql.Connection;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.ibatis.executor.statement.StatementHandler;
+import org.apache.ibatis.logging.Log;
+import org.apache.ibatis.logging.LogFactory;
+import org.apache.ibatis.plugin.Interceptor;
+import org.apache.ibatis.plugin.Intercepts;
+import org.apache.ibatis.plugin.Invocation;
+import org.apache.ibatis.plugin.Plugin;
+import org.apache.ibatis.plugin.Signature;
+import org.apache.ibatis.reflection.MetaObject;
+import org.apache.ibatis.reflection.SystemMetaObject;
+
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
+import com.baomidou.mybatisplus.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.toolkit.PluginUtils;
+
+/**
+ * <p>
+ * SQL 解析拦截器
+ * </p>
+ *
+ * @author hubin
+ * @Date 2016-08-31
+ */
+@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
+public class SqlParserInterceptor implements Interceptor {
+
+    // 日志
+    private static final Log logger = LogFactory.getLog(SqlParserInterceptor.class);
+    private static final String DELEGATE_BOUNDSQL_SQL = "delegate.boundSql.sql";
+    // SQL 解析
+    private List<AbstractSqlParser> sqlParserList;
+
+    /**
+     * 拦截 SQL 解析执行
+     */
+    @Override
+    public Object intercept(Invocation invocation) throws Throwable {
+        StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
+        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
+        // SQL 解析
+        if (CollectionUtils.isNotEmpty(sqlParserList)) {
+            String originalSql = (String) metaObject.getValue(DELEGATE_BOUNDSQL_SQL);
+            for (AbstractSqlParser sqlParser : sqlParserList) {
+                SqlInfo sqlInfo = sqlParser.optimizeSql(metaObject, originalSql);
+                if (null != sqlInfo) {
+                    originalSql = sqlInfo.getSql();
+                }
+            }
+            metaObject.setValue(DELEGATE_BOUNDSQL_SQL, originalSql);
+        }
+        return invocation.proceed();
+    }
+
+    @Override
+    public Object plugin(Object target) {
+        if (target instanceof StatementHandler) {
+            return Plugin.wrap(target, this);
+        }
+        return target;
+    }
+
+    @Override
+    public void setProperties(Properties prop) {
+        // to do nothing
+    }
+
+    public List<AbstractSqlParser> getSqlParserList() {
+        return sqlParserList;
+    }
+
+    public void setSqlParserList(List<AbstractSqlParser> sqlParserList) {
+        this.sqlParserList = sqlParserList;
+    }
+}

+ 0 - 63
src/main/java/com/baomidou/mybatisplus/plugins/TenancyInterceptor.java

@@ -1,63 +0,0 @@
-/**
- * Copyright (c) 2011-2020, 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.
- */
-package com.baomidou.mybatisplus.plugins;
-
-import java.util.Properties;
-
-import org.apache.ibatis.executor.Executor;
-import org.apache.ibatis.executor.statement.StatementHandler;
-import org.apache.ibatis.mapping.MappedStatement;
-import org.apache.ibatis.plugin.Interceptor;
-import org.apache.ibatis.plugin.Intercepts;
-import org.apache.ibatis.plugin.Invocation;
-import org.apache.ibatis.plugin.Plugin;
-import org.apache.ibatis.plugin.Signature;
-import org.apache.ibatis.session.ResultHandler;
-import org.apache.ibatis.session.RowBounds;
-
-/**
- * <p>
- * 租户拦截器,解决 SAAS 共享数据库租户场景
- * </p>
- *
- * @author hubin
- * @since 2016-08-16
- */
-@Intercepts({
-        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
-        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
-})
-public class TenancyInterceptor implements Interceptor {
-
-    @Override
-    public Object intercept(Invocation invocation) throws Throwable {
-        // TODO 待完成
-        return null;
-    }
-
-    @Override
-    public Object plugin(Object target) {
-        if (target instanceof StatementHandler) {
-            return Plugin.wrap(target, this);
-        }
-        return target;
-    }
-
-    @Override
-    public void setProperties(Properties properties) {
-        // to do nothing
-    }
-}

+ 5 - 5
src/main/java/com/baomidou/mybatisplus/plugins/pagination/optimize/JsqlParserCountOptimize.java

@@ -18,8 +18,10 @@ package com.baomidou.mybatisplus.plugins.pagination.optimize;
 import java.util.ArrayList;
 import java.util.List;
 
-import com.baomidou.mybatisplus.parser.AbstractSqlParser;
-import com.baomidou.mybatisplus.parser.SqlInfo;
+import org.apache.ibatis.reflection.MetaObject;
+
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 import com.baomidou.mybatisplus.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.toolkit.SqlUtils;
 
@@ -48,7 +50,7 @@ public class JsqlParserCountOptimize extends AbstractSqlParser {
     private static final List<SelectItem> countSelectItem = countSelectItem();
 
     @Override
-    public SqlInfo optimizeSql(String sql) {
+    public SqlInfo optimizeSql(MetaObject metaObject, String sql) {
         if (logger.isDebugEnabled()) {
             logger.debug(" JsqlParserCountOptimize sql=" + sql);
         }
@@ -93,8 +95,6 @@ public class JsqlParserCountOptimize extends AbstractSqlParser {
      * <p>
      * 获取jsqlparser中count的SelectItem
      * </p>
-     *
-     * @return
      */
     private static List<SelectItem> countSelectItem() {
         Function function = new Function();

+ 5 - 3
src/main/java/com/baomidou/mybatisplus/parser/AbstractSqlParser.java → src/main/java/com/baomidou/mybatisplus/plugins/parser/AbstractSqlParser.java

@@ -13,10 +13,11 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
-package com.baomidou.mybatisplus.parser;
+package com.baomidou.mybatisplus.plugins.parser;
 
 import org.apache.ibatis.logging.Log;
 import org.apache.ibatis.logging.LogFactory;
+import org.apache.ibatis.reflection.MetaObject;
 
 /**
  * <p>
@@ -36,9 +37,10 @@ public abstract class AbstractSqlParser {
      * 获取优化 SQL 方法
      * </p>
      *
-     * @param sql SQL 语句
+     * @param metaObject 元对象
+     * @param sql        SQL 语句
      * @return SQL 信息
      */
-    public abstract SqlInfo optimizeSql(String sql);
+    public abstract SqlInfo optimizeSql(MetaObject metaObject, String sql);
 
 }

+ 5 - 3
src/main/java/com/baomidou/mybatisplus/parser/SqlInfo.java → src/main/java/com/baomidou/mybatisplus/plugins/parser/SqlInfo.java

@@ -13,7 +13,7 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
-package com.baomidou.mybatisplus.parser;
+package com.baomidou.mybatisplus.plugins.parser;
 
 /**
  * <p>
@@ -36,15 +36,17 @@ public class SqlInfo {
         return sql;
     }
 
-    public void setSql(String sql) {
+    public SqlInfo setSql(String sql) {
         this.sql = sql;
+        return this;
     }
 
     public boolean isOrderBy() {
         return orderBy;
     }
 
-    public void setOrderBy(boolean orderBy) {
+    public SqlInfo setOrderBy(boolean orderBy) {
         this.orderBy = orderBy;
+        return this;
     }
 }

+ 4 - 0
src/main/java/com/baomidou/mybatisplus/plugins/parser/package-info.java

@@ -0,0 +1,4 @@
+/**
+ * SQL 解析相关类
+ */
+package com.baomidou.mybatisplus.plugins.parser;

+ 6 - 7
src/main/java/com/baomidou/mybatisplus/plugins/tenancy/TenancySqlParser.java

@@ -18,8 +18,10 @@ package com.baomidou.mybatisplus.plugins.tenancy;
 import java.util.ArrayList;
 import java.util.List;
 
-import com.baomidou.mybatisplus.parser.AbstractSqlParser;
-import com.baomidou.mybatisplus.parser.SqlInfo;
+import org.apache.ibatis.reflection.MetaObject;
+
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 
 import net.sf.jsqlparser.JSQLParserException;
 import net.sf.jsqlparser.expression.BinaryExpression;
@@ -62,7 +64,7 @@ public class TenancySqlParser extends AbstractSqlParser {
     private TenantInfo tenantInfo;
 
     @Override
-    public SqlInfo optimizeSql(String sql) {
+    public SqlInfo optimizeSql(MetaObject metaObject, String sql) {
         //logger.debug("old sql:{}", sql);
         Statement stmt = null;
         try {
@@ -81,9 +83,7 @@ public class TenancySqlParser extends AbstractSqlParser {
             processUpdate((Update) stmt);
         }
         //logger.debug("new sql:{}", stmt);
-        SqlInfo sqlInfo = SqlInfo.newInstance();
-        sqlInfo.setSql(stmt.toString());
-        return sqlInfo;
+        return SqlInfo.newInstance().setSql(stmt.toString());
     }
 
     /**
@@ -125,7 +125,6 @@ public class TenancySqlParser extends AbstractSqlParser {
             } else if (insert.getItemsList() != null) {
                 ((ExpressionList) insert.getItemsList()).getExpressions().add(new StringValue("," + this.tenantInfo.getTenantId() + ","));
             } else {
-                //
                 throw new RuntimeException("无法处理的 sql");
             }
         }

+ 0 - 126
src/main/java/com/baomidou/mybatisplus/plugins/tenancy/handler/RegxTenancyHandler.java

@@ -1,126 +0,0 @@
-/**
- * Copyright (c) 2011-2020, 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.
- */
-package com.baomidou.mybatisplus.plugins.tenancy.handler;
-
-import java.util.Properties;
-import java.util.regex.Pattern;
-
-import com.baomidou.mybatisplus.toolkit.PluginUtils;
-
-/**
- * <p>
- * 租户信息正则处理器
- * </p>
- *
- * @author hubin
- * @since 2017-06-20
- */
-public class RegxTenancyHandler implements TenancyHandler {
-
-    //默认过滤还是忽略 true表示按租户过滤
-    private boolean filterDefault = false;
-    private Pattern tablePatterns[];
-    private Pattern statementPatterns[];
-
-    @Override
-    public void setConfig(Properties properties) {
-        this.setFilterStatementRegexStr(PluginUtils.getProperty(properties, "filterStatementRegexStr"));
-        this.setFilterTableRegexStr(PluginUtils.getProperty(properties, "filterTableRegexStr"));
-        String filterDefault = PluginUtils.getProperty(properties, "filterDefault");
-        if (filterDefault != null) this.setFilterDefault(Boolean.valueOf(filterDefault));
-    }
-
-    @Override
-    public boolean doTable(String table) {
-        boolean isOk = filterDefault;
-        if (this.tablePatterns != null) {
-            for (Pattern p : this.tablePatterns) {
-                if (p.matcher(table).find()) {
-                    isOk = !filterDefault;
-                    break;
-                }
-            }
-        }
-        // logger.debug("table:{}  isOK:{}   tablePatterns:{}",table,isOk,tablePatterns);
-        return isOk;
-    }
-
-    @Override
-    public boolean doStatement(String statementId) {
-        boolean isOk = filterDefault;
-        if (this.statementPatterns != null) {
-            for (Pattern p : this.statementPatterns) {
-                if (p.matcher(statementId).find()) {
-                    isOk = !filterDefault;
-                    break;
-                }
-            }
-        }
-        //logger.debug("statementId:{}  isOK:{}   statementPatterns:{}",statementId,isOk,statementPatterns);
-        return isOk;
-    }
-
-    public static Pattern[] compile(String patterString) {
-        if (patterString == null) return new Pattern[]{};
-        String[] patterStrings = patterString.split(",");
-        return compile(patterStrings);
-    }
-
-    public static Pattern[] compile(String[] patterStrings) {
-        if (patterStrings == null) return new Pattern[]{};
-        Pattern[] patterns = new Pattern[patterStrings.length];
-        for (int i = 0; i < patterStrings.length; i++) {
-            Pattern pattern = Pattern.compile(patterStrings[i]);
-            patterns[i] = pattern;
-        }
-        return patterns;
-    }
-
-    public RegxTenancyHandler setFilterTableRegexStr(String tableRegexStr) {
-        if (tableRegexStr == null) {
-            return this;
-        }
-        this.tablePatterns = compile(tableRegexStr);
-        return this;
-    }
-
-    public RegxTenancyHandler setFilterTableRegexArr(String[] tableRegexArr) {
-        if (tableRegexArr == null) return this;
-        this.tablePatterns = compile(tableRegexArr);
-        return this;
-    }
-
-    public RegxTenancyHandler setFilterStatementRegexStr(String statementRegexStr) {
-        if (statementRegexStr == null) {
-            return this;
-        }
-        this.statementPatterns = compile(statementRegexStr);
-        return this;
-    }
-
-    public RegxTenancyHandler setFilterStatementRegexArr(String[] statementRegexArr) {
-        if (statementRegexArr == null) {
-            return this;
-        }
-        this.statementPatterns = compile(statementRegexArr);
-        return this;
-    }
-
-    public RegxTenancyHandler setFilterDefault(boolean filterDefault) {
-        this.filterDefault = filterDefault;
-        return this;
-    }
-}

+ 0 - 60
src/main/java/com/baomidou/mybatisplus/plugins/tenancy/handler/TenancyHandler.java

@@ -1,60 +0,0 @@
-/**
- * Copyright (c) 2011-2020, 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.
- */
-package com.baomidou.mybatisplus.plugins.tenancy.handler;
-
-import java.util.Properties;
-
-/**
- * <p>
- * 租户信息处理器
- * </p>
- *
- * @author hubin
- * @since 2017-06-20
- */
-public interface TenancyHandler {
-
-    /**
-     * <p>
-     * 配置设置
-     * </p>
-     *
-     * @param properties mybatis Interceptor setProperties
-     */
-    void setConfig(Properties properties);
-
-    /**
-     * <p>
-     * 按照表名处理
-     * </p>
-     *
-     * @param table 表名
-     * @return true 执行,false 不执行
-     */
-    boolean doTable(String table);
-
-
-    /**
-     * <p>
-     * 按照statementId处理
-     * </p>
-     *
-     * @param statementId mybatis statementId
-     * @return true 执行,false 不执行
-     */
-    boolean doStatement(String statementId);
-
-}

+ 0 - 4
src/main/java/com/baomidou/mybatisplus/plugins/tenancy/handler/package-info.java

@@ -1,4 +0,0 @@
-/**
- * 租户信息处理相关类
- */
-package com.baomidou.mybatisplus.plugins.tenancy.handler;

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

@@ -16,8 +16,8 @@
 package com.baomidou.mybatisplus.toolkit;
 
 import com.baomidou.mybatisplus.enums.SqlLike;
-import com.baomidou.mybatisplus.parser.AbstractSqlParser;
-import com.baomidou.mybatisplus.parser.SqlInfo;
+import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 import com.baomidou.mybatisplus.plugins.pagination.Pagination;
 import com.baomidou.mybatisplus.plugins.pagination.optimize.JsqlParserCountOptimize;
 
@@ -56,7 +56,7 @@ public class SqlUtils {
                 COUNT_SQL_PARSER = new JsqlParserCountOptimize();
             }
         }
-        return COUNT_SQL_PARSER.optimizeSql(originalSql);
+        return COUNT_SQL_PARSER.optimizeSql(null, originalSql);
     }
 
     /**

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

@@ -3,7 +3,7 @@ package com.baomidou.mybatisplus.test;
 import org.junit.Assert;
 import org.junit.Test;
 
-import com.baomidou.mybatisplus.parser.SqlInfo;
+import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
 import com.baomidou.mybatisplus.plugins.pagination.optimize.JsqlParserCountOptimize;
 
 /**