Mybatis中的foreach用法可以用于动态拼接SQL语句中的IN条件,常用的技巧有:
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="ids" item="id" index="index" open="(" separator="," close=")">
#{id} - #{index}
</foreach>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>