zoukankan      html  css  js  c++  java
  • 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>

    END

  • 相关阅读:
    jQuery基础
    深入理解JVM内存模型(jmm)和GC
    oracle,哪些操作会导致索引失效?
    systemd
    一个我小时候玩过的我是猪不然关机的软件,我高仿了一个,超简单。
    自己写的求最大值实现,用到了模板函数。
    poj 1695
    poj 1192
    poj 1239
    poj 1170
  • 原文地址:https://www.cnblogs.com/yangyongjie/p/11947054.html
Copyright © 2011-2022 走看看