在SQL开发过程中,我们会经常使用到in进行搜索,Mybatis中提供了foreach功能,它允许你指定一个集合,然后对集合中的数据进行迭代赋值,如何使用这一功能,很简单,主要是细节要注意。我们先看下foreach的语法
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
foreach元素的属性包含 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名,非限定词
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
open表示该语句以什么开始,这边使用"(",则会在sql进行拼接加上"(", 如where id in (
separator表示在每次进行迭代之间以什么符号作为分隔 符,如如where id in ( 1,
close表示以什么结束,这边使用"(",则会在list遍历后进行拼接加上")",如where id in (1,2)
collection表示要遍历的集合
针对collection参数,我们需要考虑入参,而不能随便写,如果如参数List<String>则这样设定
如果参数的类型是List集合, 则在使用时,collection属性要必须指定为 list
<select id="findByIds" resultMap="User">
Select
id ,name
from t_a where id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
以上的查询,最终会转换成这样的sql,
select id ,name from t_a where id in (1,2)
但是实际开发中,我们不能局限于list集合,也有可能是数组,数组的方式只要做一下修改即可
<foreach item="item" index="index" collection="array" ....