美文网首页
[转]MyBatis使用Map传参批量插入数据

[转]MyBatis使用Map传参批量插入数据

作者: crMiao | 来源:发表于2021-05-05 14:28 被阅读0次

    参数部分 java

    if(obj.getItemList() != null && obj.getItemList().size() > 0){
                                
        Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
        map.put("groupId", groupId);
            map.put("itemList", obj.getItemList());
        trendItemMapper.insertGroupAfterItemList(map);
    }
    

    MyBatis的Mapper.xml

    <insert id="insertGroupAfterItemList" parameterType="java.util.Map">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
          SELECT LAST_INSERT_ID()
        </selectKey>
        insert into trend_item
            (trend_group_id, element_id, element_name,create_user_id,data_type)
        values
        <foreach collection="itemList" item="item" index="index" separator=",">
            (
                #{groupId},#{item.elementId},#{item.elementName},#{userId},#{item.dataType}
            )
        </foreach>
      </insert>
    

    foreach标签解释:

    foreach标签可使用的地方:例:批量删除 如 in 、批量添加

    foreach标签属性: item,index,collection,open,separator,close。

    item:每个遍历生成的对象。必填

    index:指定一个名字,用于表示在迭代过程中,当前的迭代次数。从零开始递增。

    collection:输入对象中的集合属性。必填

    open:开始遍历时拼接的字符串,

    separator:遍历时两个对象之间需要设置的分隔符。必填

    close:结束遍历时拼接的字符串,

    collection 不同情况下,该属性的值是不一样的,主要有一下3种情况:

    1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

    2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

    3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map

    使用批量插入执行的SQL语句应该等价于:

     insert into trend_item
            (trend_group_id, element_id, element_name,create_user_id,data_type)
     values
     (?,?,?,?,? ),(?,?,?,?,? ),(?,?,?,?,? ),(?,?,?,?,? )
    

    相关文章

      网友评论

          本文标题:[转]MyBatis使用Map传参批量插入数据

          本文链接:https://www.haomeiwen.com/subject/kwgkdltx.html