form1.cn
Make a little progress every day

mybatis的xml中sql语句中in的写法

23th of July 2017 Java Java 7264

传入的参数必须为collection类型的,List 、Map,如果你在地址栏接收到的是字符串,那你需要转为collection类型


在XML中主要使用foreach标签

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

foreach的结果为:(23,46,75,43) 这种形式


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

# item表示集合中每一个元素进行迭代时的别名.
# index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
# collection 为传进来的collection参数的 类型*
# open表示该语句以什么开始
# separator表示在每次进行迭代之间以什么符号作为分隔符
# close表示以什么结束


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

传入参数的代码为:

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

XML为:

<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>


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

传入的参数代码为:

List<Object> addArray(String[]  ids);

XML为:

<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>


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

获得的参数为String:

String str = "1,2,3,4";
Map  map = new HashMap();
map.put("ids",str.spit(","));

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

传入的参数代码为:

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

XML为:

<select id="addMap" resultType="map">
select  from tp_trade where  id in 
<foreach  item="item" collection="ids" index="index"  open="(" separator="," close=")">
#{item}
</foreach>
</select>


ids就是数组集合,使用item遍历即可