MyBatis中<foreach>语句用法及‘Parameter 'item' not found’问题求助
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
Add
@Paramto 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 integercommentCount, so the map value should beInteger, notString):@MapKey("workId") public Map<Integer, Integer> getTest(@Param("workIds") List<Integer> workIds) throws DataAccessException;Update the
<foreach>Collection Attribute
Change thecollectionvalue 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
listvariable is empty when callinggetTest(), the generated SQL will have an invalidIN ()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 thecommentCount(an integer). UsingMap<Integer, Integer>will prevent unexpected type casting errors.
内容的提问来源于stack exchange,提问作者T.qeibo

