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

MyBatis中<foreach>语句用法及‘Parameter 'item' not found’问题求助

Fixing "Parameter 'item' not found" in MyBatis Tag

Let's break down why you're hitting this error and how to fix it quickly.

The Root Cause

When you pass a single List parameter to a MyBatis mapper method without using the @Param annotation, MyBatis wraps the list in a map with a default key of "list". However, this default behavior can be inconsistent across MyBatis versions, or your setup might not be picking up the default key correctly. This leads MyBatis to fail resolving the item variable in your <foreach> tag (since it can't find the underlying collection to iterate over).

Step-by-Step Fix

  1. Add @Param to Your Mapper Interface Parameter
    Explicitly name your list parameter so MyBatis can reference it clearly. Also, fix the return type mismatch (your query returns an integer commentCount, so the map value should be Integer, not String):

    @MapKey("workId")
    public Map<Integer, Integer> getTest(@Param("workIds") List<Integer> workIds) throws DataAccessException;
    
  2. Update the <foreach> Collection Attribute
    Change the collection value in your XML to match the name you specified in @Param:

    <select id="getTest" resultType="java.util.HashMap" parameterType="java.util.List">
        <![CDATA[
            SELECT COUNT(*) AS commentCount, WORK_ID AS workId
            FROM TB_COMMENT
            WHERE TB_COMMENT.WORK_ID IN
            <foreach item="item" collection="workIds" separator="," open="(" close=")">
                #{item}
            </foreach>
            GROUP BY TB_COMMENT.WORK_ID
        ]]>
    </select>
    

Additional Tips

  • Guard Against Empty Lists: If your list variable is empty when calling getTest(), the generated SQL will have an invalid IN () clause. Add a check before the method call:
    Map<Integer, Integer> test = new HashMap<>();
    if (!list.isEmpty()) {
        test = statusMapper.getTest(list);
    }
    
  • Verify Result Type Matching: Your original return type Map<Integer, String> doesn't align with the commentCount (an integer). Using Map<Integer, Integer> will prevent unexpected type casting errors.

内容的提问来源于stack exchange,提问作者T.qeibo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:17:33