【问题标题】:Accessing list element by index in myBatis-mapping在 myBatis-mapping 中按索引访问列表元素
【发布时间】:2019-12-16 08:38:25
【问题描述】:

我在 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 的大小相同。我在 myBatis-mapping 中通过索引访问 ages 的元素有些困难。我已经尝试过括号,如第一个 sn-p 中所示。我也尝试了#{ages}.get(#index),但没有任何效果。有可能吗?

【问题讨论】:

    标签: mybatis


    【解决方案1】:

    #{}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>
    

    请参阅FAQ entry 了解#{}${} 之间的区别。


    尽管考虑到驱动程序支持语法,这可能会起作用,但它基本上是一个带有许多占位符的大 PreparedStatement,并且效率不高,尤其是当列表中有很多项目时。
    如果是这种情况,您应该考虑使用批量更新。详情请见this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-04
      • 2017-04-23
      • 2023-03-20
      • 2017-04-18
      • 1970-01-01
      • 2019-07-28
      • 2016-12-11
      相关资源
      最近更新 更多