mybatis中foreach标签详解
轉(zhuǎn)載自:https://blog.csdn.net/gwd1154978352/article/details/75408498
foreach的主要用在構(gòu)建in條件中,它可以在SQL語(yǔ)句中進(jìn)行迭代一個(gè)集合。
foreach元素的屬性主要有 item,index,collection,open,separator,close。
- item表示集合中每一個(gè)元素進(jìn)行迭代時(shí)的別名,
- index指 定一個(gè)名字,用于表示在迭代過(guò)程中,每次迭代到的位置,
- open表示該語(yǔ)句以什么開(kāi)始,
- separator表示在每次進(jìn)行迭代之間以什么符號(hào)作為分隔 符,
- close表示以什么結(jié)束。
在使用foreach的時(shí)候最關(guān)鍵的也是最容易出錯(cuò)的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的,主要有一下3種情況:
以封裝成map,實(shí)際上如果你在傳入?yún)?shù)的時(shí)候,在breast里面也是會(huì)把它封裝成一個(gè)Map的,map的key就是參數(shù)名,所以這個(gè)時(shí)候collection屬性值就是傳入的List或array對(duì)象在自己封裝的map里面的key 下面分別來(lái)看看上述三種情況的示例代碼:
1.單參數(shù)List 類(lèi)型
<select id="dynamicForeachTest" resultType="Blog">select * from t_blog where id in<foreach collection="list" index="index" item="item" open="(" separator="," close=")">#{item} </foreach> </select>上述collection的值為list,對(duì)應(yīng)的Mapper是這樣的
public List dynamicForeachTest(List ids);
測(cè)試代碼:
2.單參數(shù)array數(shù)組的類(lèi)型:
<select id="dynamicForeach2Test" resultType="Blog">select * from t_blog where id in<foreach collection="array" index="index" item="item" open="(" separator="," close=")">#{item}</foreach> </select>上述collection為array,對(duì)應(yīng)的Mapper代碼:
public List dynamicForeach2Test(int[] ids);
對(duì)應(yīng)的測(cè)試代碼:
3.自己把參數(shù)封裝成Map的類(lèi)型
<select id="dynamicForeach3Test" resultType="Blog">select * from t_blog where title like "%"#{title}"%" and id in<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">#{item}</foreach></select>上述collection的值為ids,是傳入的參數(shù)Map的key,對(duì)應(yīng)的Mapper代碼:
public List dynamicForeach3Test(Map params);
對(duì)應(yīng)測(cè)試代碼:
總結(jié)
以上是生活随笔為你收集整理的mybatis中foreach标签详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: produces在@requestMap
- 下一篇: Java JDBC中,MySQL字段类型