Mybatis foreach批量插入与批量更新

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>

批量更新多条记录:

  1、MySQL连接url上加上&allowMultiQueries=true

  2、语句

<update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update tableName
        <set>
            name=${item.name},
            name2=${item.name2}
        </set>
        where id = ${item.id}
    </foreach>      
</update>

 

 

END

 

posted @ 2019-11-28 09:49  杨岂  阅读(9711)  评论(0编辑  收藏  举报