1、foreach的屬性
item:集合中元素迭代時的別名,必填
index:在list和array中,index是元素的序號;在map中,index是元素的key,可選
open:foreach代碼的開始符號,一般是 ‘(’ 並和 ')' 合用,常用在in(),values()時,可選
separator:元素之間的分隔符,可選
close:foreach代碼的關閉符號,一般是 ')' 並和 '('合用,常用在in(),values()時,可選
collection:foreach迭代的對象,作為入參時,List對象默認用 list 代替,數組對象用 array代替。Map對象沒有默認的鍵。
同時可以在作為入參時使用@param("xxx")來設置鍵,這時,默認的list、array將會失效。
官方說明:
注意 你可以將一個 List 實例或者數組作為參數對象傳給 MyBatis,當你這么做的時候,MyBatis 會自動將它包裝在一個 Map 中並以名稱為鍵。List 實例將會以“list”作為鍵,而數組實例的鍵將是“array”。
2、示例:
dao:
int batchInsert(List<Coupon> coupons);
Mapper:
<insert id="batchInsertMiCoupon" parameterType="java.util.List"> INSERT INTO mi_coupon ( xxx ) values <foreach collection="list" item="item" index="index" separator=","> ( #{item.xxx,jdbcType=VARCHAR} ) </foreach> </insert>
另外需要注意,批量插入List集合的大小不要超過500,200為宜,否則插入也會很慢,過多的話甚至一條都不能入庫且沒有報錯信息。
3、mybatis 批量入庫參數一個為集合,一個為字符串的情況
// Map組裝參數 Map<String, Object> param = new HashMap<>(4); param.put("subProductIdsList", subProductIdsList); param.put("comProductId", comProductId); // dao @Override public int batchInsert(Map<String, Object> param) { return this.getSqlSessionTemplate().insert(NAMESPACE + ".batchInsert", param); } // Mapper.xml <insert id="batchInsert"> insert into xxx(com_product_id, sub_product_id) values <foreach collection="subProductIdsList" item="item" index="index" separator=","> ( #{comProductId}, #{item,jdbcType=VARCHAR} ) </foreach> </insert>
批量更新
<!--批量更新分集視頻狀態為審核中--> <update id="batchUpdateAuditStatus" parameterType="java.util.List"> update cp_video set audit_status='1' where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item,jdbcType=BIGINT} </foreach> </update>
END