首页 > 编程技术 > java

解决mybatis-plus 查询耗时慢的问题

发布时间:2021-7-4 10:00

mybatis-plus 查询耗时慢

1、现象

查出30000多条id

然后用

EntityWrapper ew = new EntityWrapper<>();
 ew.in(TableFieldConstant.F_AUTH_RESULT_ID, ids);

查询会很慢

2、原因

跟了一下mybatis-plus源码

 protected String formatSqlIfNeed(boolean need, String sqlStr, Object... params) {
        if (need && !StringUtils.isEmpty(sqlStr)) {
            if (ArrayUtils.isNotEmpty(params)) {
                for(int i = 0; i < params.length; ++i) {
                    String genParamName = "MPGENVAL" + this.paramNameSeq.incrementAndGet();
                    sqlStr = sqlStr.replace(String.format("{%s}", i), String.format("#{%s.paramNameValuePairs.%s}", this.getParamAlias(), genParamName));
                    this.paramNameValuePairs.put(genParamName, params[i]);
                }
            }
 
            return sqlStr;
        } else {
            return null;
        }
    }

问题出现在

sqlStr = sqlStr.replace(String.format("{%s}", i), String.format("#{%s.paramNameValuePairs.%s}", this.getParamAlias(), genParamName));

对replace 测试 发现当数据量大时替换会很耗时 测试的遍历了30000次拼接从1到30000 替换耗时20多秒

对 apache-commons-lang 的StringUtis.replace测试是耗时7秒多

3、总结

把使用mybaits 批量查询改为 手写sql查询 之后问题解决

使用mybatis-plus批量操作时要谨慎 能写sql尽量写sql

这个跟mybatis-plus 的小伙伴提了问题后已经解决 可以升级jar版本 3.x

mybatis-plus 处理大数据量太慢

大批量数据插入方法是Mybatis的foreach拼接SQL

我发现不管改成Mybatis Batch提交或者原生JDBC Batch的方法都不起作用,实际上在插入的时候仍然是一条条记录的插,速度远不如原来Mybatis的foreach拼接SQL的方法。

// 第一步判断更新或添加
 String[] splitUserId = userGroup.getUserId().split(",");
 String[] spiltUserName = userGroup.getUserName().split(",");
 if (StringUtils.isBlank(userGroup.getId())) {
  userGroup.setNum(spiltUserName.length);
  userGroupMapper.insert(userGroup);
 } else {
  userGroup.setNum(spiltUserName.length);
  userGroupMapper.updateById(userGroup);
 }
 /* 第二部删除中间表信息,字段冗余 */

 Map<String, Object> columnMap = new HashMap<String, Object>();
 columnMap.put("USER_GROUP_ID", userGroup.getId());
 groupUsersService.removeByMap(columnMap);

 /* 第三步,批量保存中间表 */

 if (splitUserId.length != 0) {
  List<GroupUsers> groupUsersList = Lists.newArrayList();
  for (int i = 0; i < splitUserId.length; i++) {
   GroupUsers gu = new GroupUsers();
   gu.setUserId(splitUserId[i]);
   gu.setUserName(spiltUserName[i]);
   gu.setUserGroupId(userGroup.getId());
   groupUsersList.add(gu);
  }
  groupUsersService.saveBatch(groupUsersList);
 }

1、就是这样的一种情景也很符合大部分的开发场景,可就是1000条数据的情况下用了8秒 ,这可能与计算机的性能有很大的关系,但就是如此也不至于用八秒钟,那么用户体验会很惨的。

2、JDBC连接URL字符串中需要新增一个参数:

rewriteBatchedStatements=true url: jdbc:mysql://192.168.1.143:3306/rt_xxxxxx_test?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true

3、MySQL的JDBC连接的url中要加rewriteBatchedStatements参数,并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。

4、MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。

只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL

另外这个选项对INSERT/UPDATE/DELETE都有效

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: