mybatis - 在 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);
集合的大小fnames
和ages
是一样的。ages
我在 myBatis-mapping 中按索引访问元素有一些困难。我已经尝试过括号,如第一个片段中所示。我也尝试过#{ages}.get(#index)
,但没有任何效果。有可能吗?
解决方案
#{}
是 中的占位符(即?
)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
并且效率不高,尤其是当列表中有很多项目时。
如果是这种情况,您应该考虑使用批量更新。有关详细信息,请参阅此答案。
推荐阅读
- python - SQLAlchemy 'on_conflict_do_update' 不更新
- git - 将一个问题的 Squash 提交合并为一个问题
- python - Python中的空变量列表
- count - Powerbi 可以计算单元格中特定文本的多次出现吗?
- mysql - 2个表之间的Phpmyadmin关系
- reactjs - 如何在我的应用程序上创建自定义键盘反应原生?
- woocommerce - woocommerce中的小数分隔符为逗号
- javascript - 如何将数组中的真假字符串解析为布尔值
- kubernetes - Kubernetes 入口块在创建状态
- c# - 从没有对象的 PropertyInfo 中获取值