mybatis里in关键字拼接id问题
我们一般会把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标签✅