MyBatis 中的动态SQL(使用foreach)

Dynamic SQL in MyBatis (using foreach)

我想遍历列表,但出现异常

org.apache.ibatis.mapping.SqlMapperException: The expression 'list' evaluated to a null value.

我的java代码:

public  List<SearchVO> getSearchResultByParams(List<String> selectedGroups) {
    Map map = new HashMap(1);
    map.put("selectedGroups", selectedGroups);
    return MyMapper.getSearchResultByParams(map);
}

MyMapper.xml:

<select id="getSearchResultByParams" parameterType="map" resultMap="SearchResultMap">
    SELECT *
    FROM WORK
    WHERE ID IN 
         <foreach item="selectedGroups" collection="list" open="(" separator="," close=")">
            #{selectedGroups}
        </foreach>
</select>

首先确保你在 mybatis-config 文件中为 java.util.HashMap 设置了别名 map typeAliases tag

<select id="getSearchResultByParams" parameterType="map" resultMap="SearchResultMap">
    SELECT *
    FROM WORK
    WHERE ID IN 
         <foreach collection="selectedGroups" item="item" index="index" open="(" separator="," close=")">
            #{item}
        </foreach>
</select>

集合必须是您在地图中列出的关键字

该文档可能会帮助您 http://mybatis.github.io/mybatis-3/dynamic-sql.html

我添加

后类似的错误为我解决了
public SearchResultMap getSearchResultByParams(@Param("selectedGroups") List<String> selectedGroups) 

我的意思是 @Param 注释