mybatis批量更新方案
发布时间:2021-12-05 10:53:15 所属栏目:教程 来源:互联网
导读:我们知道循环中操作db会导致连接数满,严重影响数据库性能。所以在对db进行DQL与DML时,根据业务逻辑尽量批量操作,这里我们介绍下使用mybatis批量更新mysql的两种方式。 方式一: update id=updateBatch parameterType=Java.util.List foreach collection=li
我们知道循环中操作db会导致连接数满,严重影响数据库性能。所以在对db进行DQL与DML时,根据业务逻辑尽量批量操作,这里我们介绍下使用mybatis批量更新mysql的两种方式。 方式一: <update id="updateBatch" 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 id="updateBatch" 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链接,但是数据量太大效率不高。 ![]() (编辑:青岛站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |