Dynamic SQL in MyBatis (using foreach)

3.4k views Asked by At

I want to iterate through the list, but I am getting exception

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

My java code:

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>
2

There are 2 answers

0
Zy Zhao On BEST ANSWER

first make sure you had set alias map for java.util.HashMap in mybatis-config file 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>

collection must be the key for you list in your map

the doc may help you http://mybatis.github.io/mybatis-3/dynamic-sql.html

0
mcvkr On

Similar error resolved for me after I added

public SearchResultMap getSearchResultByParams(@Param("selectedGroups") List<String> selectedGroups) 

I mean with the @Param annotation