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>