You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mybatis中@Select查询where子句使用Map报参数未找到错误

解决方案

方案一:修正EntrySet遍历的参数引用

当遍历entrySet()时,foreach的item对应的是Map.Entry对象,index是循环的索引序号(并非Map的key),因此需要通过item.key和item.value来获取键值对:

@Select("""
       SELECT CURRENCY_CD,COUNTRY_CD,FEE_RATE_VAL FROM FEE
               WHERE (COUNTRY_CD, CURRENCY_CD) IN               
       <foreach item="entry" collection="countryCurrencyCodes.entrySet()" separator="," open="(" close=")">
                    (#{entry.key}, #{entry.value})
       </foreach>
       """)
@Results(value = {
    @Result(property = "currencyCd", column = "CURRENCY_CD"),
    @Result(property = "countryCd", column = "COUNTRY_CD"),
    @Result(property = "feeRateValue", column = "FEE_RATE_VAL")
 })
List<Fee> getFeeOf(@Param("countryCurrencyCodes") Map<String, String> countryCurrencyCodes);

方案二:直接遍历Map(更简洁)

Mybatis支持直接遍历Map,此时index对应Map的key,item对应Map的value,无需调用entrySet(),同时要为foreach添加open="("和close=")"保证SQL语法合法:

@Select("""
       SELECT CURRENCY_CD,COUNTRY_CD,FEE_RATE_VAL FROM FEE
               WHERE (COUNTRY_CD, CURRENCY_CD) IN               
       <foreach item="currencyCd" index="countryCd" collection="countryCurrencyCodes" separator="," open="(" close=")">
                    (#{countryCd},#{currencyCd})
       </foreach>
       """)
@Results(value = {
    @Result(property = "currencyCd", column = "CURRENCY_CD"),
    @Result(property = "countryCd", column = "COUNTRY_CD"),
    @Result(property = "feeRateValue", column = "FEE_RATE_VAL")
 })
List<Fee> getFeeOf(@Param("countryCurrencyCodes") Map<String, String> countryCurrencyCodes);

错误原因

  1. 你之前指定collection="countryCurrencyCodes.entrySet()"时,foreach的index是循环的数字序号,并非Map的key,item是Map.Entry对象,因此#{countryCd}找不到对应参数,正确引用应为#{item.key}。
  2. 原foreach缺少open="("和close=")",即使参数绑定成功,生成的SQL也会因格式错误无法执行。

内容的提问来源于stack exchange,提问作者Pat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:43:18