我们知道循环中操作db会导致连接数满,严重影响数据库性能。所以在对db进行DQL与DML时,根据业务逻辑尽量批量操作,这里我们介绍下使用mybatis批量更新mysql的两种方式。
方式一:
<update  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>
但Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加 &allowMultiQueries=true 这个才可以执行。
方式二:
<update parameterType="java.util.List">
       update
       <include refid="tableName"/>
       <trim prefix="set" suffixOverrides=",">
           <trim prefix="update_acc =case" suffix="end,">
               <foreach collection="list" item="item">
                   <if test="item.updateAcc!=null">
                       when clue_id=#{item.clueId} then #{item.updateAcc}
                   </if>
               </foreach>
           </trim>
           <trim prefix="update_time =case" suffix="end,">
               <foreach collection="list" item="item">
                   <if test="item.updateTime!=null">
                       when clue_id=#{item.clueId} then #{item.updateTime}
                   </if>
               </foreach>
           </trim>
       </trim>
       <where>
           <foreach collection="list" separator="or" item="item">
               (org_id = #{item.orgId}
               and clue_id = #{item.clueId})
           </foreach>
       </where>
   </update>
其中when...then...是sql中的"switch" 语法。这里借助mybatis的<foreach>语法来拼凑成了批量更新的sql,这种方式不需要修改mysql链接,但是数据量太大效率不高。
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx

