首页 > 解决方案 > 在 myBatis-mapping 中按索引访问列表元素

问题描述

我在 myBatis 中有以下映射。

<update id="updatePersons" parameterType="Map">
    begin
    <foreach item="fname" collection="fnames" index="index" separator=";">
        update person set age = #{ages}[#{index}] where fname = #{fname}
    </foreach>;
    end;
</update>

它应该更新所有名字与作为参数传递的名字匹配的人的年龄。

以及Java中的相应调用:

Map<String, List<String>> map = new HashMap<>();
List<String> fnames = new ArrayList<>();
List<Integer> ages = new ArrayList<>();
map.put("fnames", fnames);
map.put("ages", ages);
session.update("person.updatePersons", map);

集合的大小fnamesages是一样的。ages我在 myBatis-mapping 中按索引访问元素有一些困难。我已经尝试过括号,如第一个片段中所示。我也尝试过#{ages}.get(#index),但没有任何效果。有可能吗?

标签: mybatis

解决方案


#{}是 中的占位符(即?PreparedStatement,因此表达式#{ages}[#index}]被转换?[?]为不是有效的 SQL 语法。
正确的语法是......

<update id="updatePersons">
  begin
  <foreach item="fname" collection="fnames" index="index" separator=";">
    update person set age = #{ages[${index}]} where fname = #{fname}
  </foreach>;
  end;
</update>

请参阅常见问题解答条目#{}以了解和之间的区别${}


尽管考虑到驱动程序支持该语法,这可能会起作用,但它基本上是一个包含许多占位符的单个 bigPreparedStatement并且效率不高,尤其是当列表中有很多项目时。
如果是这种情况,您应该考虑使用批量更新。有关详细信息,请参阅此答案


推荐阅读