Mybatis批量增加、批量更新、批量删除和查询

时间:2025-03-22 08:32:59

之前项目由于需要处理短时间内大量数据入库的问题。想到了Mybatis的批量操作。这里对这些操作进行一下记录,重点是批量增加和更新。

一、批量增加

    <!-- 批量增加操作 -->
    <insert id="batchInsertUsers" parameterType="">
        insert into user(userName,password) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{},#{})
        </foreach>
    </insert>

二、批量删除

<!-- 批量删除操作 -->
    <delete id="batchDeleteUsers" parameterType="">
        delete from user where id in
        <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
            #{}
        </foreach>
    </delete>

三、批量更新

批量更新网上查到的大部分是这种形式:

    <!-- 批量更新操作 -->
    <update id="batchUpdateUsers" parameterType="">
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update user
        <set>
            userName = #{}, password = #{}
        </set>
        where id = #{}
        </foreach>
    </update>

这种更新方式说是批量更新。其实实质上是一条记录执行一次update的sql,对数据库而言,还是多条sql,性能不好,容易造成阻塞。Mysql没有提供直接的方法来实现批量更新,但是我们可以通过使用 case when来实现这一功能:

UPDATE course
    SET name = CASE id 
        WHEN 1 THEN 'name1'
        WHEN 2 THEN 'name2'
        WHEN 3 THEN 'name3'
    END, 
    title = CASE id 
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3)

代码示例如下:

<update id="updateBatch" parameterType="list">
            update user
            <trim prefix="set" suffixOverrides=",">
             <trim prefix="id=case" suffix="end,">
                 <foreach collection="list" item="i" index="index">
                         <if test="!=null">
                          when id=#{} then #{}
                         </if>
                 </foreach>
              </trim>
              <trim prefix=" name=case" suffix="end,">
                 <foreach collection="list" item="i" index="index">
                         <if test="!=null">
                          when id=#{} then #{}
                         </if>
                 </foreach>
              </trim>
             </trim>
            where
            <foreach collection="list" separator="or" item="i" index="index" >
              id=#{}
          </foreach>
</update>

四、批量查询

    <!-- 批量查询操作 -->
    <select id="batchSelectUsers" resultType="User">
        select *
        from user where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{}
        </foreach>
    </select>