需求说明
如果想在mybatis中使用in语句,就必须传入 in(1,2,3) 类似的参数。实现的原理就是利用mybatsi动态拼接的语法。实现方式有两种
- 遍历数组
- 拼接字符串
方式1:遍历数组
WHERE
<if test="id!=0 and results != null ">
result in
<foreach collection="results" item="item" index="index"
open="(" close=")" separator=",">
${item}
</foreach>
and
</if>
这里results 是数组类型[1,2,3,4],通过foreach,在前后拼接了(),分隔符采用逗号。最终解析结果是
WHERE result in (1,3,4,5)
使用 的 原 因 是 , 的原因是, 的原因是,原样输出。
方式2:拼接字符串参数
WHERE
<if test="id!=0 and results != null ">
result in (${resultstr})
</if>
这里resultstr是一个字符串:“1,2,3”,拼接后
WHERE result in (1,2,3)
注意点
拼接字符串的方式仅适用于 数值类型的遍历。否则无法无法拼接成 in (‘1’,‘2’,‘3’)。
无论哪种方式都仅仅是利用mybatis语法实现拼接sql。最终sql语句正确才能执行成功。需要多次打印sql语句不断调整。
参考
https://blog.csdn.net/sinat_32034679/article/details/78716151
https://blog.csdn.net/cxws110/article/details/88826257