ToB企服应用市场:ToB评测及商务社交产业平台

标题: 使用Mybatis自定义插件实现不侵入业务的公共参数自动追加 [打印本页]

作者: 渣渣兔    时间: 2024-3-4 21:56
标题: 使用Mybatis自定义插件实现不侵入业务的公共参数自动追加
背景

后台业务开发的过程中,往往会遇到这种场景:需要记录每条记录产生时间、修改时间、修改人及添加人,在查询时查询出来。
以往的做法通常是手动在每个业务逻辑里耦合上这么一块代码,也有更优雅一点的做法是写一个拦截器,然后在Mybatis拦截器中为实体对象中的公共参数进行赋值,但最终依然需要在业务SQL上手动添加上这几个参数,很多开源后台项目都有类似做法。
这种做法往往不够灵活,新增或修改字段时每处业务逻辑都需要同步修改,业务量大的话这么改非常麻烦。
最近在我自己的项目中写了一个Mybatis插件,这个插件能够实现不修改任何业务逻辑就能实现添加或修改时数据库公共字段的赋值,并能在查询时自动查询出来。
实现原理

Mybatis提供了一系列的拦截器,用于实现在Mybatis执行的各个阶段允许插入或修改自定义逻辑。
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
我这里用的是Executor,它能做到在所有数据库操作前后执行一些逻辑,甚至可以修改Mybatis的上下文参数后继续执行。
在Mybaits的拦截器中,可以拿到MappedStatement对象,这里面包含了一次数据库操作的原始SQL以及实体对象与结果集的映射关系,为了实现公共参数自动携带,我们就需要在拦截器中修改原始SQL:
以及修改实体对象与结果集的映射关系,做到自动修改查询语句添加公共字段后能够使Mybatis将查出的公共字段值赋给实体类。
简单来说就是修改MappedStatement中的SqlSource以及ResultMap
修改SqlSource

在SqlSource中,包含了原始待执行的SQL,需要将它修改为携带公共参数的SQL。
需要注意的是Mybatis的SqlSource、ResultMap中的属性仅允许初次构造SqlSource对象时进行赋值,后续如果需要修改只能通过反射或者新构造一个对象替换旧对象的方式进行内部参数修改。
直接贴出来代码,这里新构造了SqlSource对象,在里面实现了原始SQL的解析修改:
SQL的动态修改使用了JSQLParser将原始SQL解析为AST抽象语法树后做参数追加,之后重新解析为SQL,使用自定义SqlSource返回修改后的SQL实现SQL修改
  1. static class ModifiedSqlSourceV2 implements SqlSource {
  2.         private final MappedStatement mappedStatement;
  3.         private final Configuration configuration;
  4.         public ModifiedSqlSourceV2(MappedStatement mappedStatement, Configuration configuration) {
  5.             this.mappedStatement = mappedStatement;
  6.             this.configuration = configuration;
  7.         }
  8.         @Override
  9.         public BoundSql getBoundSql(Object parameterObject) {
  10.             // 获取原始的 BoundSql 对象
  11.             BoundSql originalBoundSql = mappedStatement.getSqlSource().getBoundSql(parameterObject);
  12.             // 获取原始的 SQL 字符串
  13.             String originalSql = originalBoundSql.getSql();
  14.             log.debug("公共参数添加 - 修改前SQL:{}", originalSql);
  15.             // 创建新的 BoundSql 对象
  16.             String modifiedSql;
  17.             try {
  18.                 modifiedSql = buildSql(originalSql);
  19.                 log.debug("公共参数添加 - 修改后SQL:{}", modifiedSql);
  20.             } catch (JSQLParserException e) {
  21.                 log.error("JSQLParser解析修改SQL添加公共参数失败, 继续使用原始SQL执行" , e);
  22.                 modifiedSql = originalSql;
  23.             }
  24.             BoundSql modifiedBoundSql = new BoundSql(configuration, modifiedSql,
  25.                     originalBoundSql.getParameterMappings(), parameterObject);
  26.             // 复制其他属性
  27.             originalBoundSql.getAdditionalParameters().forEach(modifiedBoundSql::setAdditionalParameter);
  28.             modifiedBoundSql.setAdditionalParameter("_parameter", parameterObject);
  29.             return modifiedBoundSql;
  30.         }
  31.         private String buildSql(String originalSql) throws JSQLParserException {
  32.             Statement statement = CCJSqlParserUtil.parse(originalSql);
  33.             switch(mappedStatement.getSqlCommandType()) {
  34.                 case INSERT -> {
  35.                     if(statement instanceof Insert insert) {
  36.                         insert.addColumns(new Column(CREATE_BY_COLUMN), new Column(CREATE_TIME_COLUMN));
  37.                         ExpressionList expressionList = insert.getItemsList(ExpressionList.class);
  38.                         Timestamp currentTimeStamp = new Timestamp(System.currentTimeMillis());
  39.                         if (!expressionList.getExpressions().isEmpty()) {
  40.                             // 多行插入 行构造器解析
  41.                             if (expressionList.getExpressions().get(0) instanceof RowConstructor) {
  42.                                 expressionList.getExpressions().forEach((expression -> {
  43.                                     if (expression instanceof RowConstructor rowConstructor) {
  44.                                         rowConstructor.getExprList().getExpressions().add(new StringValue(getCurrentUser()));
  45.                                         rowConstructor.getExprList().getExpressions().add(new TimestampValue().withValue(currentTimeStamp));
  46.                                     }
  47.                                 }));
  48.                             } else {
  49.                                 // 其余默认单行插入
  50.                                 expressionList.addExpressions(new StringValue(getCurrentUser()), new TimestampValue().withValue(currentTimeStamp));
  51.                             }
  52.                         }
  53.                         return insert.toString();
  54.                     }
  55.                 }
  56.                 case UPDATE -> {
  57.                     if(statement instanceof Update update) {
  58.                         List<UpdateSet> updateSetList = update.getUpdateSets();
  59.                         UpdateSet updateBy = new UpdateSet(new Column(UPDATE_BY_COLUMN), new StringValue(getCurrentUser()));
  60.                         Timestamp currentTimeStamp = new Timestamp(System.currentTimeMillis());
  61.                         UpdateSet updateTime = new UpdateSet(new Column(UPDATE_TIME_COLUMN), new TimestampValue().withValue(currentTimeStamp));
  62.                         updateSetList.add(updateBy);
  63.                         updateSetList.add(updateTime);
  64.                         return update.toString();
  65.                     }
  66.                 }
  67.                 case SELECT -> {
  68.                     if(statement instanceof Select select) {
  69.                         SelectBody selectBody = select.getSelectBody();
  70.                         if(selectBody instanceof PlainSelect plainSelect) {
  71.                             TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
  72.                             List<String> tableNames = tablesNamesFinder.getTableList(select);
  73.                             List<SelectItem> selectItems = plainSelect.getSelectItems();
  74.                             tableNames.forEach((tableName) -> {
  75.                                 String lowerCaseTableName = tableName.toLowerCase();
  76.                                 selectItems.add(new SelectExpressionItem().withExpression(new Column(new Table(tableName), CREATE_BY_COLUMN)).withAlias(new Alias(lowerCaseTableName + "_" + CREATE_BY_COLUMN)));
  77.                                 selectItems.add(new SelectExpressionItem().withExpression(new Column(new Table(tableName), CREATE_TIME_COLUMN)).withAlias(new Alias(lowerCaseTableName + "_" + CREATE_TIME_COLUMN)));
  78.                                 selectItems.add(new SelectExpressionItem().withExpression(new Column(new Table(tableName), UPDATE_BY_COLUMN)).withAlias(new Alias(lowerCaseTableName + "_" + UPDATE_BY_COLUMN)));
  79.                                 selectItems.add(new SelectExpressionItem().withExpression(new Column(new Table(tableName), UPDATE_TIME_COLUMN)).withAlias(new Alias(lowerCaseTableName + "_" + UPDATE_TIME_COLUMN)));
  80.                             });
  81.                             return select.toString();
  82.                         }
  83.                     }
  84.                 }
  85.                 default -> {
  86.                     return originalSql;
  87.                 }
  88.             }
  89.             return originalSql;
  90.         }
  91. }
复制代码
修改ResultMap

ResultMap中存放了结果列与映射实体类属性的对应关系,这里为了自动生成公共属性的结果映射,直接根据当前ResultMap中存储的结果映射实体类的名称作为表名,自动建立与结果列的映射关系。
就是说数据库表对应的实体类的名字需要与数据库表保持一致(但是实体类名可以是数据库表的名字的驼峰命名,如表user_role的实体类需要命名为UserRole),只要遵守这个命名规则即可实现查询结果中自动携带公共参数值
如下为添加公共参数结果映射的代码
  1. private static List<ResultMapping> addResultMappingProperty(Configuration configuration, List<ResultMapping> resultMappingList, Class<?> mappedType) {
  2.         // resultMappingList为不可修改对象
  3.         List<ResultMapping> modifiableResultMappingList = new ArrayList<>(resultMappingList);
  4.         String []checkList = {CREATE_BY_PROPERTY, CREATE_TIME_PROPERTY, UPDATE_BY_PROPERTY, UPDATE_TIME_PROPERTY};
  5.         boolean hasAnyTargetProperty = Arrays.stream(checkList).anyMatch((property) -> ReflectionUtils.findField(mappedType, property) != null);
  6.         // 用于防止映射目标为基本类型却被添加映射 导致列名规则 表名_列名 无法与映射的列名的添加规则 映射类型名_列名 相照应
  7.         // 从而导致映射类型为基本类型时会生成出类似与string_column1的映射名 而产生找不到映射列名与实际结果列相照应的列名导致mybatis产生错误
  8.         // 规则: 仅映射类型中包含如上四个字段其一时才会添加映射
  9.         if(hasAnyTargetProperty) {
  10.             // 支持类型使用驼峰命名
  11.             String currentTable = upperCamelToLowerUnderscore(mappedType.getSimpleName());
  12.             // 映射方式 表名_公共字段名 在实体中 表名与实体名相同 则可完成映射
  13.             modifiableResultMappingList.add(new ResultMapping.Builder(configuration, CREATE_BY_PROPERTY, currentTable + "_" + CREATE_BY_COLUMN, String.class).build());
  14.             modifiableResultMappingList.add(new ResultMapping.Builder(configuration, CREATE_TIME_PROPERTY, currentTable + "_" + CREATE_TIME_COLUMN, Timestamp.class).build());
  15.             modifiableResultMappingList.add(new ResultMapping.Builder(configuration, UPDATE_BY_PROPERTY, currentTable + "_" + UPDATE_BY_COLUMN, String.class).build());
  16.             modifiableResultMappingList.add(new ResultMapping.Builder(configuration, UPDATE_TIME_PROPERTY, currentTable + "_" + UPDATE_TIME_COLUMN, Timestamp.class).build());
  17.         }
  18.         return modifiableResultMappingList;
  19. }
复制代码
构建MappedStatement

原本的由Mybatis创建的MappedStatement无法直接修改,因此这里手动通过ResultMap.Builder()构造一个新的MappedStatement,同时保持其余参数不变,只替换SqlSource、ResultMap为先前重新创建的对象。
  1. public MappedStatement buildMappedStatement(Configuration newModifiedConfiguration, MappedStatement mappedStatement) {
  2.         SqlSource modifiedSqlSource = new ModifiedSqlSourceV2(mappedStatement, newModifiedConfiguration);
  3.         List<ResultMap> modifiedResultMaps = mappedStatement.getResultMaps().stream().map((resultMap) -> {
  4.             List<ResultMapping> resultMappingList = resultMap.getResultMappings();
  5.             // 为每个resultMap中的resultMappingList添加公共参数映射
  6.             List<ResultMapping> modifiedResultMappingList = addResultMappingProperty(newModifiedConfiguration, resultMappingList, resultMap.getType());
  7.             return new ResultMap.Builder(newModifiedConfiguration, resultMap.getId(), resultMap.getType(), modifiedResultMappingList, resultMap.getAutoMapping()).build();
  8.         }).toList();
  9.         // 构造新MappedStatement 替换SqlSource、ResultMap、Configuration
  10.         MappedStatement.Builder newMappedStatementBuilder = new MappedStatement.Builder(newModifiedConfiguration, mappedStatement.getId(), modifiedSqlSource, mappedStatement.getSqlCommandType())
  11.                 .cache(mappedStatement.getCache()).databaseId(mappedStatement.getDatabaseId()).dirtySelect(mappedStatement.isDirtySelect()).fetchSize(mappedStatement.getFetchSize())
  12.                 .flushCacheRequired(mappedStatement.isFlushCacheRequired())
  13.                 .keyGenerator(mappedStatement.getKeyGenerator())
  14.                 .lang(mappedStatement.getLang()).parameterMap(mappedStatement.getParameterMap()).resource(mappedStatement.getResource()).resultMaps(modifiedResultMaps)
  15.                 .resultOrdered(mappedStatement.isResultOrdered())
  16.                 .resultSetType(mappedStatement.getResultSetType()).statementType(mappedStatement.getStatementType()).timeout(mappedStatement.getTimeout()).useCache(mappedStatement.isUseCache());
  17.         if(mappedStatement.getKeyColumns() != null) {
  18.             newMappedStatementBuilder.keyColumn(StringUtils.collectionToDelimitedString(Arrays.asList(mappedStatement.getKeyColumns()), ","));
  19.         }
  20.         if(mappedStatement.getKeyProperties() != null) {
  21.             newMappedStatementBuilder.keyProperty(StringUtils.collectionToDelimitedString(Arrays.asList(mappedStatement.getKeyProperties()), ","));
  22.         }
  23.         if(mappedStatement.getResultSets() != null) {
  24.             newMappedStatementBuilder.resultSets(StringUtils.collectionToDelimitedString(Arrays.asList(mappedStatement.getResultSets()), ","));
  25.         }
  26.         return newMappedStatementBuilder.build();
  27. }
复制代码
到这里为止,已经完全实现了修改原始SQL、修改结果映射的工作了,将修改后的MappedStatement对象往下传入到invoke()即可但是还能改进。
改进

在Mybatis拦截器中可以通过MappedStatement.getConfiguration()拿到整个Mybatis的上下文,在这个里面可以拿到所有Mybatis的所有SQL操作的映射结果以及SQL,可以一次性修改完后,将Configuration作为一个缓存使用,每次有请求进入拦截器后就从Configuration获取被修改的MappedStatement后直接invoke,效率会提升不少。
经给改进后,除了应用启动后执行的第一个SQL请求由于需要构建Configuration会慢一些,之后的请求几乎没有产生性能方面的影响。
现在唯一的性能消耗是每次执行请求前Mybatis会调用我们自己重新定义的SqlSource.getBoundSql()将原始SQL解析为AST后重新构建生成新SQL的过程了,这点开销几乎可忽略不计。如果想更进一步的优化,可以考虑将原始SQL做key,使用Caffeine、Guava缓存工具等方式将重新构建后的查询SQL缓存起来(Update/Insert由于追加有时间参数的原因,不能被缓存),避免多次重复构建SQL带来的开销
完整实现

经过优化后,整个插件已经比较完善了,能够满足日常使用,无论是单表查询,还是多表联查,嵌套查询都能够实现无侵入的参数追加,目前仅实现了创建人、创建时间、修改人、修改时间的参数追加&映射绑定,如有需要的可以自行修改。
我把它放到了GitHub上,并附带有示例项目:https://github.com/Random-pro/ExtParamInterctptor
觉得好用的欢迎点点Star
使用的人多的话,后续会将追加哪些参数做成动态可配置的,等你们反馈
插件使用示例

所有的新增操作均会被自动添加创建人、创建时间。更新操作则会被自动添加更新人、更新时间。正常使用Mybatis操作即可,与原先无任何差别就不在这里给出示例了,如果需要示例请前往我在GitHub上的示例项目。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4