我們一般會把ids集合用StrUtil.join(‘,’)轉成"1,2,3"這種形式 然后放入in中 我們會這么寫:
select id, nick_name, icon from tb_user where id in (#{ids}) order by FIELD(id, #{ids})
結果發現sql執行是這樣的:
select id, nick_name, icon from tb_user where id in ('1011, 1022') order by FIELD(id, '1011, 1022')
先上正確玩法?:
<select id="findByIds" resultType="com.hmdp.dto.UserDTO">select id, nick_name, icon from tb_user where id in<foreach collection="ids" open="(" close=")" separator="," item="id">#{id}</foreach>order by FIELD(id,<foreach collection="ids" separator="," item="id">#{id}</foreach>)
</select>
現在說一下為什么會造成這種現象, 原因是mybatis為了防止sql注入而對字符串拼接的片段會在首尾兩端添加一對引號 這樣就不存在and 1=1永真了 即’1011, 1012’的來源 所以在xml里寫sql遍歷集合還是要用foreach標簽?