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
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
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遍歷即可。