DynamicTableNameParser.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.baomidou.mybatisplus.extension.parsers;
  17. import java.util.Collection;
  18. import java.util.Map;
  19. import org.apache.ibatis.reflection.MetaObject;
  20. import com.baomidou.mybatisplus.core.parser.ISqlParser;
  21. import com.baomidou.mybatisplus.core.parser.SqlInfo;
  22. import com.baomidou.mybatisplus.core.toolkit.Assert;
  23. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  24. import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
  25. import lombok.Data;
  26. import lombok.experimental.Accessors;
  27. /**
  28. * 动态表名 SQL 解析器
  29. *
  30. * @author jobob
  31. * @since 2019-04-23
  32. */
  33. @Data
  34. @Accessors(chain = true)
  35. public class DynamicTableNameParser implements ISqlParser {
  36. private Map<String, ITableNameHandler> tableNameHandlerMap;
  37. @Override
  38. public SqlInfo parser(MetaObject metaObject, String sql) {
  39. Assert.isFalse(CollectionUtils.isEmpty(tableNameHandlerMap), "tableNameHandlerMap is empty.");
  40. if (allowProcess(metaObject)) {
  41. Collection<String> tables = new TableNameParser(sql).tables();
  42. if (CollectionUtils.isNotEmpty(tables)) {
  43. boolean sqlParsed = false;
  44. String parsedSql = sql;
  45. for (final String table : tables) {
  46. ITableNameHandler tableNameHandler = tableNameHandlerMap.get(table);
  47. if (null != tableNameHandler) {
  48. parsedSql = tableNameHandler.process(metaObject, parsedSql, table);
  49. sqlParsed = true;
  50. }
  51. }
  52. if (sqlParsed) {
  53. return SqlInfo.newInstance().setSql(parsedSql);
  54. }
  55. }
  56. }
  57. return null;
  58. }
  59. /**
  60. * 判断是否允许执行
  61. * <p>例如:逻辑删除只解析 delete , update 操作</p>
  62. *
  63. * @param metaObject 元对象
  64. * @return true
  65. */
  66. public boolean allowProcess(MetaObject metaObject) {
  67. return true;
  68. }
  69. }