MyBatis batch operations

       When using MyBatis as a data processing framework, batch processing can be used to improve efficiency when operating a large amount of data insertion, update and other time-consuming tasks. The batch processing of MyBatis is mainly implemented using the foreach tag.
 

        The foreach element is very powerful, it allows you to specify a collection, declare collection items and index variables that can be used in the element body. It also allows you to specify open and closed strings to match and place delimiters between iterations. This element is smart so it doesn't accidentally append extra separators.

 

        Note: You can pass any iterable object (such as list, set, etc.) and any dictionary or array object to foreach as a collection parameter. When using iterable objects or arrays, index is the current iteration number, and the value of item is the element obtained in this iteration. When using a dictionary (or a collection of Map.Entry objects), index is the key and item is the value.
 
Foreach entry introduction:
1. If a single parameter is passed in and the parameter type is a List, the value of the collection attribute is list.
2. If a single parameter is passed in and the parameter type is an array array, the attribute value of collection is array.
3. If the incoming parameters are multiple, we need to encapsulate them into a Map, of course, a single parameter can also be encapsulated into a map.
 
Let's take the Post class of the blog as an example. Post has three attributes: id, msg, and type.
1. Batch query
<select id="selectPostBatch" resultType="domain.blog.Post">
  SELECT * FROM POST
  WHERE id in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
 
2. Bulk insert
<insert id="savePostBatch" parameterType="list">
  insert into POST
  (msg,type)
  values
    <foreach item="item" index="index" collection="list" separator=",">
        #{item.msg},#{item.type}
  </foreach>
</insert>
 
3. Batch update
<update id="updatePostBatch" parameterType="list">
       <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update post
        <trim prefix="set" suffixOverrides=",">
            <if test="item.msg!=null">
                msg=#{item.msg},
            </if>
            <if test="item.type!=null">
                type=#{item.type},
            </if>
        </trim>
        where id=#{item.id}
        </foreach>
</update>
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326679204&siteId=291194637