• collection:要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键,该参数必选;
  • item:循环体中的具体对象,支持属性的点路径访问,该参数必选;
  • index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选;
  • open:foreach代码的开始符号,一般是(和close=")"合用,该参数可选;
  • close:foreach代码的关闭符号,一般是)和open="("合用,该参数可选;
  • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,该参数可选;

情况一:

Dao的方法:参数是一个数组类型的

Mybatis的参数为数组时使用foreach_java

其主要是在in条件中,可以在SQL语句中迭代一个集合;

<select id="getStringByguid" resultType="java.lang.String">
select guid from kjt_inventory
where
ORDERNO in
<foreach collection="array" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>

</select>

Mybatis的参数为数组时使用foreach_sql语句_02

情况二:

Dao的方法:参数是一个List类型的

Mybatis的参数为数组时使用foreach_java_03

其主要是在in条件中,可以在SQL语句中迭代一个集合;

<select id="getStringByOrder" resultType="java.lang.String">
select
orderno from kjt_inventory
where
id in
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>

只要就是collection改变了

Mybatis的参数为数组时使用foreach_sql语句_04

情况三:

Dao的方法:参数是一个Map类型的

Mybatis的参数为数组时使用foreach_sql语句_05

map的key(键)就是参数名,因此collection属性值就是传入的List或array对象在自己封装的map里面的key

<select id="getOrder" resultType="java.lang.String">
select
* from kjt_inventory
where
sku in
<foreach collection="sku" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>

Mybatis的参数为数组时使用foreach_sql语句_06