源码分析 Mybatis 的 foreach 为何会出现性能问题

背景

最近在作一个相似于综合报表之类的东西,须要查询全部的记录(数据库记录有限制),大概有1W条记录,该报表须要三个表的数据,也就是根据这 1W 个 ID 去执行查询三次数据库,其中,有一条查询 SQL 是本身写,其余两条是根据别人提供的接口进行查询,刚开始的时候,没有多想,直接使用 in 进行查询,使用 Mybatis 的 foreach 语句;项目中使用的是 jsonrpc 来请求数据,在测试的时候,发现总是请求不到数据,日志抛出的是 jsonrpc 超时异常,继续查看日志发现,是被阻塞在上面的三条SQL查询中。spring

在之前分析 Mybatis 的源码的时候,了解到,Mybatis 的 foreach 会有性能问题,因此改了下 SQL,直接在代码中拼接SQL,而后在 Mybatis 中直接使用 # 来获取,替换 class 测试了下,果真一会儿就能查询出数据。sql

前提

这里先不考虑使用 in 好很差,如何去优化 in,如何使用 exists 或 inner join 进行代替等,这里就只是考虑使用了 in 语句,且使用了 Mybatis 的 foreach 语句进行优化,其实 foreach 的优化很简单,就是把 in 后面的语句在代码里面拼接好,在配置文件中直接经过 #{xxx} 或 ${xxx} 看成字符串直接使用便可。数据库

测试

在分析 foreach 源码以前,先构造个数据来看看它们的区别有多大。json

建表语句:bash

CREATE TABLE person
(
    id int(11) PRIMARY KEY NOT NULL,
    name varchar(50),
    age int(11),
    job varchar(50)
);复制代码

插入 1W 条数据:mybatis

POJO 类:架构

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private int id;
    private String name;
    private String job;
    private int age;
}复制代码

方式一

经过原始的方式,使用 foreach 语句:并发

1. 在 dao 里面定义方法:app

List<Person> queryPersonByIds(@Param("ids") List<Integer> ids);
复制代码

2. 配置文件SQL:分布式

<select id="queryPersonByIds" parameterType="list" resultMap="queryPersonMap">
	select * from person where 1=1
	<if test="ids != null and ids.size() > 0">
		and id in
		<foreach collection="ids" item="item" index="index" separator="," open="(" close=")">
			#{item}
		</foreach>
	</if>
</select>复制代码

3. 执行 main 方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
public class MainTest {

    @Autowired
    private IPersonService personService;

    @Test
    public void test(){
        // 构造 1W 个 ID
        List<Integer> ids = new ArrayList<>();
        for (int i = 1; i <= 10000; i++) {
            ids.add(i);
        }
        long start = System.currentTimeMillis();
        
        // 执行三次
        personService.queryPersonByIds(ids);
        personService.queryPersonByIds(ids);
        personService.queryPersonByIds(ids);

        long end = System.currentTimeMillis();
        System.out.println(String.format("耗时:%d", end - start));
    }
}
结果:耗时:2853复制代码

能够看到经过 foreach 的方法,大概须要 3s

方式二

在代码中封装 SQL ,在配置文件中 经过 ${xxx} 来获取:

1. 在 dao 添加方法:

List<Person> queryPersonByIds2(@Param("ids") String ids);
复制代码

2. 配置文件SQL:

<select id="queryPersonByIds2" parameterType="String" resultMap="queryPersonMap">
	select * from person where 1=1
	<if test="ids != null and ids != ''">
	  and id in ${ids}
	</if>
</select>复制代码

3. 执行 main 方法:

@Test
public void test_3(){
	// 拼接 SQL 
	StringBuffer sb = new StringBuffer();
	sb.append("(");
	for (int i = 1; i < 10000; i++) {
		sb.append(i).append(",");
	}
	sb.deleteCharAt(sb.toString().length() - 1);
	sb.append(")");
    // 最终的 SQL 为 (1,2,3,4,5...)

	long start2 = System.currentTimeMillis();

    // 执行三次
	personService.queryPersonByIds2(sb.toString());
	personService.queryPersonByIds2(sb.toString());
	personService.queryPersonByIds2(sb.toString());

	long end2 = System.currentTimeMillis();
	System.out.println(String.format("耗时:%d", end2 - start2));
}
结果:耗时:360复制代码

经过拼接 SQL,使用 ${xxx} 的方式,执行一样的 SQL ,耗时大概 360 ms

方式三

在代码中封装 SQL ,在配置文件中 经过 #{xxx} 来获取:

1. 在 dao 中添加方法:

List<Person> queryPersonByIds3(@Param("ids") String ids);
复制代码

2. 配置文件SQL:

<select id="queryPersonByIds3" parameterType="String" resultMap="queryPersonMap">
	select * from person where 1=1
	<if test="ids != null and ids != ''">
		and id in (#{ids})
	</if>
</select>复制代码

3. 执行 main 方法:

@Test
public void test_3(){
    // 拼接 SQL
	StringBuffer sb2 = new StringBuffer();
	for (int i = 1; i < 10000; i++) {
		sb2.append(i).append(",");
	}
	sb2.deleteCharAt(sb2.toString().length() - 1);
    // 最终的SQL为 1,2,3,4,5....

	long start3 = System.currentTimeMillis();

	personService.queryPersonByIds3(sb2.toString());
	personService.queryPersonByIds3(sb2.toString());
	personService.queryPersonByIds3(sb2.toString());

	long end3 = System.currentTimeMillis();
	System.out.println(String.format("耗时:%d", end3 - start3));
}
结果:耗时:30复制代码

经过拼接 SQL,使用 #{xxx} 的方式,执行一样的 SQL ,耗时大概 30 ms

总结

经过上面三种方式能够看到,使用不一样的方式,耗时的差异仍是麻大的,最快的是 拼接 SQL,使用 #{xxx} 看成字符串处理,最慢的是 foreach。为何 foreach 会慢那么多呢,后面再分析源码的时候再进行分析;而这里一样是拼接 SQL 的方式,#{xxx} 和 ${xxx} 耗时却相差 10 倍左右;咱们知道,Mybatis 在解析 # 和 $ 这两种不一样的符号时,采用不一样的处理策略;使用过 JDBC 的都知道,经过 JDBC 执行 SQL 有两种方式: Statment 对象和PreparedStatment 对象, PreparedStatment 表示预编译的SQL,包含的SQL已经预编译过了,SQL 中的参数部分使用 ?进行占位,以后使用 setXXX 进行赋值,当使用 Statement 对象时,每次执行一个SQL命令时,都会对它进行解析和编译。全部 PreparedStatment 效率要高一些。那么 Mybatis 在解析 # 和 $ 的时候,分别对应的是这两种对象,# 被解析成 PreparedStatment 对象,经过 ? 进行占位,以后再赋值,而 $ 被解析成 Statement ,经过直接拼接SQL的方式赋值,因此,为何一样是经过在代码中拼接 SQL ,# 和 $ 的耗时不一样的缘由。

PS:上面只是介绍了三种方式,应该没有人问,拼接SQL为 (1,2,3,4,5),在配置SQL中经过 #{xxx} 来获取吧

foreach 源码解析

下面来看下 foreach 是如何被解析的,最终解析的 SQL 是什么样的:

在 Mybatis 中,foreach 属于动态标签的一种,也是最智能的其中一种,Mybatis 每一个动态标签都有对应的类来进行解析,而 foreach 主要是由 ForEachSqlNode 负责解析。

ForeachSqlNode 主要是用来解析 <foreach> 节点的,先来看看 <foreach> 节点的用法:

<select id="queryPersonByIds" parameterType="list" resultMap="queryPersonMap">
	select * from person where 1=1
	<if test="ids != null and ids.size() > 0">
		and id in
		<foreach collection="ids" item="item" index="index" separator="," open="(" close=")">
			#{item}
		</foreach>
	</if>
</select>复制代码

最终被 数据库执行的 SQL 为 select * from person where 1=1 and id in (1,2,3,4,5)

先来看看它的两个内部类:

PrefixedContext

该类主要是用来处理前缀,好比 "(" 等。

private class PrefixedContext extends DynamicContext {   
   private DynamicContext delegate;
    // 指定的前缀
    private String prefix;
    // 是否处理过前缀
    private boolean prefixApplied;
    // .......

    @Override
    public void appendSql(String sql) {
      // 若是尚未处理前缀,则添加前缀
      if (!prefixApplied && sql != null && sql.trim().length() > 0) {
        delegate.appendSql(prefix);
        prefixApplied = true;
      }
       // 拼接SQL
      delegate.appendSql(sql);
    }
}复制代码

FilteredDynamicContext

FilteredDynamicContext 是用来处理 #{} 占位符的,可是并未绑定参数,只是把 #{item} 转换为 #{_frch_item_1} 之类的占位符。

private static class FilteredDynamicContext extends DynamicContext {
    private DynamicContext delegate;
    //对应集合项在集合的索引位置
    private int index;
    // item的索引
    private String itemIndex;
    // item的值
    private String item;
    //.............
    // 解析 #{item}
    @Override
    public void appendSql(String sql) {
      GenericTokenParser parser = new GenericTokenParser("#{", "}", new TokenHandler() {
        @Override
        public String handleToken(String content) {
          // 把 #{itm} 转换为 #{__frch_item_1} 之类的
          String newContent = content.replaceFirst("^\\s*" + item + "(?![^.,:\\s])", itemizeItem(item, index));
           // 把 #{itmIndex} 转换为 #{__frch_itemIndex_1} 之类的
          if (itemIndex != null && newContent.equals(content)) {
            newContent = content.replaceFirst("^\\s*" + itemIndex + "(?![^.,:\\s])", itemizeItem(itemIndex, index));
          }
          // 再返回 #{__frch_item_1} 或 #{__frch_itemIndex_1}
          return new StringBuilder("#{").append(newContent).append("}").toString();
        }
      });
      // 拼接SQL
      delegate.appendSql(parser.parse(sql));
    }
  private static String itemizeItem(String item, int i) {
    return new StringBuilder("__frch_").append(item).append("_").append(i).toString();
  }
}复制代码

ForeachSqlNode

了解了 ForeachSqlNode 它的两个内部类以后,再来看看它的实现:

public class ForEachSqlNode implements SqlNode {
  public static final String ITEM_PREFIX = "__frch_";
  // 判断循环的终止条件
  private ExpressionEvaluator evaluator;
  // 循环的集合
  private String collectionExpression;
  // 子节点
  private SqlNode contents;
  // 开始字符
  private String open;
  // 结束字符
  private String close;
  // 分隔符
  private String separator;
  // 本次循环的元素,若是集合为 map,则index 为key,item为value
  private String item;
  // 本次循环的次数
  private String index;
  private Configuration configuration;

  // ...............

  @Override
  public boolean apply(DynamicContext context) {
    // 获取参数
    Map<String, Object> bindings = context.getBindings();
    final Iterable<?> iterable = evaluator.evaluateIterable(collectionExpression, bindings);
    if (!iterable.iterator().hasNext()) {
      return true;
    }
    boolean first = true;
    // 添加开始字符串
    applyOpen(context);
    int i = 0;
    for (Object o : iterable) {
      DynamicContext oldContext = context;
      if (first) {
        // 若是是集合的第一项,则前缀prefix为空字符串
        context = new PrefixedContext(context, "");
      } else if (separator != null) {
        // 若是分隔符不为空,则指定分隔符
        context = new PrefixedContext(context, separator);
      } else {
          // 不指定分隔符,在默认为空
          context = new PrefixedContext(context, "");
      }
      int uniqueNumber = context.getUniqueNumber();  
      if (o instanceof Map.Entry) {
        // 若是集合是map类型,则将集合中的key和value添加到bindings参数集合中保存
        Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) o;
        // 因此循环的集合为map类型,则index为key,item为value,就是在这里设置的
        applyIndex(context, mapEntry.getKey(), uniqueNumber);
        applyItem(context, mapEntry.getValue(), uniqueNumber);
      } else {
        // 不是map类型,则将集合中元素的索引和元素添加到 bindings集合中
        applyIndex(context, i, uniqueNumber);
        applyItem(context, o, uniqueNumber);
      }
      // 调用 FilteredDynamicContext 的apply方法进行处理
      contents.apply(new FilteredDynamicContext(configuration, context, index, item, uniqueNumber));
      if (first) {
        first = !((PrefixedContext) context).isPrefixApplied();
      }
      context = oldContext;
      i++;
    }
     // 添加结束字符串
    applyClose(context);
    return true;
  }

  private void applyIndex(DynamicContext context, Object o, int i) {
    if (index != null) {
      context.bind(index, o); // key为idnex,value为集合元素
      context.bind(itemizeItem(index, i), o); // 为index添加前缀和后缀造成新的key
    }
  }

  private void applyItem(DynamicContext context, Object o, int i) {
    if (item != null) {
      context.bind(item, o);
      context.bind(itemizeItem(item, i), o);
    }
  }
}复制代码

因此该例子:

<select id="queryPersonByIds" parameterType="list" resultMap="queryPersonMap">
	select * from person where 1=1
	<if test="ids != null and ids.size() > 0">
		and id in
		<foreach collection="ids" item="item" index="index" separator="," open="(" close=")">
			#{item}
		</foreach>
	</if>
</select>复制代码

解析以后的 SQL 为:

select * from person where 1=1 and id in (#{__frch_item_0}, #{__frch_item_1}, #{__frch_item_2}, #{__frch_item_3}, #{__frch_item_4})

以后在经过 PreparedStatment 的 setXXX 来进行赋值。

因此,到这里,知道了 Mybatis 在解析 foreach 的时候,最后仍是解析成了

#
的方式,可是为何仍是很慢呢,这是由于须要循环解析 #{__frch_item_0} 之类的占位符,foreach 的集合越大,解析越慢。既然知道了须要解析占位符,为什么不本身拼接呢,因此就能够在代码中拼接好,而再也不使用 foreach 啦。

因此,Mybatis 在解析 foreach 的时候,底层仍是会解析成

#
号的形式而不是
$
的形式,既然知道了这个,若是 须要 foreach 的集合很大,就可使用代码拼接 SQL ,使用
(#{xxx}) 的方式进行获取,不要再拼接成 (1,2,3,4,5) 再使用 ${xxx} 的方式啦。

欢迎工做一到五年的Java工程师朋友们加入Java进阶高级架构:416843702 群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码, MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料) 合理利用本身每一分每一秒的时间来学习提高本身,不要再用"没有时间“来掩饰本身思想上的懒惰!趁年轻,使劲拼,给将来的本身一个交代! 

相关文章
相关标签/搜索