轉自:https://www.cnblogs.com/xuehuashanghe/p/12882762.html
使用 mybatis 時,如果要使用到 in 寫法,要使用 foreach ,里面幾個參數,看了很多地方,都說的不清不楚,自己最后各種測試,這里詳細說下:
(1)collection = “” ,這個參數是 dao 層(mapper)接口方法里面傳過來的集合參數,如果dao 層傳的參數只有一個,這里寫關鍵字 list(如果是數組,寫 array)
例子:
dao 層:User getInfo(List<Integer> user_ids)
collection = "list"
【
如果有多個參數,並且使用了 @Param 注解(import org.apache.ibatis.annotations.Param),則這里要寫注解里面的參數!
例子: dao 層 :User getInfo(@Param("user_ids")List<Integer> user_ids,@Param("xxx")String xxx)
collection = "user_ids"
】
(2)item = “” ,集合里面的單個值,給下面 #{ } 用
(3)index = "" ,這個是遍歷的下標,舉個簡單的例子立刻明白,就是平時 for 循環,我們定義的 i 一樣
例子: for(int i = 0 ;i < 10 ; i ++){
}
因此這個參數隨便定義都可以,有就行
(4)open separator close 這3個比較好理解,就是 ( , , ,) 這樣子啦,拼接括號,中間逗號隔開的意思
select:
List<CityCollection> getCollectionByIdList(@Param("idList")List<Integer> idList);
SELECT
c.id,
c.city_image_url cityImageUrl,
c.province_name provinceName,
c.country_name countryName,
c.city_name cityName,
ce.city_name enCityName,
ce.country_name enCountryName,
ce.province_name enProvinceName
FROM
t_c c
LEFT JOIN t_ci_en ce ON ce.id = c.id
WHERE
c.id IN
<foreach collection="idList" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
ORDER BY
field (
c.id,
<foreach collection="idList" item="item" separator=",">
#{item}
</foreach>
)
刪除:
Integer deleteAllCollectionByIdListAndUserId(@Param("idList")List<Integer> idList, @Param("userId")Integer userId);
DELETE
FROM
t_collection_city
WHERE
city_id IN
<foreach collection="idList" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
AND
user_id = #{userId}