mybatis的xml中sql语句中in的写法(迭代遍历)

这里使用 foreach标签


<foreach  item="item" collection="listTag" index="index"  open="(" separator="," close=")">

#{item}

</foreach>


foreach元素的属性主要有 item,index,collection,open,separator,close。

item表示集合中每一个元素进行迭代时的别名.

index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.

open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.

close表示以什么结束.

1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

<select id="addList" resultType="map">

select * from tp_trade where  id in 

<foreach  item="item" collection="list" index="index"  open="(" separator="," close=")">#{item}</foreach>

</select>

传入参数的代码为:

List<Object>  addList(List<Object> ids);

2.如果传入的是单参数且参数类型是一个Array数组的时候,collection属性值为array


<select id="addArray" resultType="map">

select * from tp_trade where  tt_type in 

<foreach  item="item" collection="array" index="index"  open="(" separator="," close=")">#{item}</foreach>

</select>

传入的参数代码为:
List<Object> addArray(String[]  ids);

3.如果多个参数,我们会封装成map类型,然后在把需要遍历的list或者array封装到map中。

传入的参数代码为:

String str = "1,2,3,4";

Map  map = new HashMap();

map.put("type",str.spit(","));

再把封装好map传入到方法中。

List<Object> addMap(Map<String,Object> map);


<select id="addMap" resultType="map">

select * from tp_trade where  type in 

<foreach  item="item" collection="type" index="index"  open="(" separator="," close=")">#{item}</foreach>

</select>

type就是数组集合,使用item遍历即可。
---------------------
转载:https://blog.csdn.net/android_hongshao/article/details/46974935 

猜你喜欢

转载自www.cnblogs.com/wangzhengyu/p/10417365.html