<日积月累>MySQL动态语句foreach各种用法比较

349 阅读1分钟

  1. 单参数List的类型:
<select id="dynamicForeachTest" resultType="Blog">  
    select * from t_blog where id in  
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
</select>

 上述collection的值为list,对应的Mapper是这样的

  1. 单参数array数组的类型:
<select id="dynamicForeach2Test" resultType="Blog">  
    select * from t_blog where id in  
    <foreach collection="array" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
</select>  

上述collection为array,对应的Mapper代码:

3. 自己把参数封装成Map的类型

<select id="dynamicForeach3Test" resultType="Blog">  
    select * from t_blog where title like "%"#{title}"%" and id in  
    <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
</select>  

上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码: