在程序中封裝了一個List集合對象,然後需要把該集合中的實體插入到數據庫中,項目使用了Spring MVC +MyBatis的配置,使用MyBatis批量插入。
主要是用foreach標籤,它可以在SQL語句中進行迭代一個集合。
foreach元素的屬性主要有 item,index,collection,open,separator,close。
item表示集合中每一個元素進行迭代時的別名,
index指 定一個名字,用於表示在迭代過程中,每次迭代到的位置,
open表示該語句以什麼開始,
separator表示在每次進行迭代之間以什麼符號作爲分隔 符,
close表示以什麼結束,
在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的。
1.如果傳入的是單參數且參數類型是一個List的時候,collection屬性值爲list
2.如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值爲array
舉例:
一:批量插入一個集合
方法:
public Long insertPriceHistoryList(List<TmallPriceHistory> list) ;
參數:
List<TmallPriceHistory> list;
SQL語句:
<insert id="insertPriceHistoryList" parameterType="java.util.List" >
insert into
`tmall_price_history_copy`
(
`sid`,
`third_request_history_sid`,
`shopinProSid`,
`shopinSku`,
`tmallNum_iid`,
`shopinProDetailSid`,
`tmallSkuId`,
`tmallSkuProperties`,
`propertiesName`,
`price`,
`createTime`,
`operateTime`,
`tmallPriceTime`,
`status`,
`memo`,
`type`
) values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.sid},
#{item.third_request_history_sid},
#{item.shopinProSid},
#{item.shopinSku},
#{item.tmallNum_iid},
#{item.shopinProDetailSid},
#{item.tmallSkuId},
#{item.tmallSkuProperties},
#{item.propertiesName},
#{item.price},
#{item.createTime},
#{item.operateTime},
#{item.tmallPriceTime},
#{item.status},
#{item.memo},
#{item.type}
)
</foreach>
</insert>
方法:
public Long deletePriceHistoryList(List<TmallPriceHistory> priceHistoryList) ;
參數:
List<TmallPriceHistory> priceHistoryList;
SQL語句:
<delete id="deletePriceHistoryList" parameterType="java.util.List">
delete
from
`tmall_price_history`
where
`sid`
in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item.sid}
</foreach>
</delete>