脚本宝典收集整理的这篇文章主要介绍了mybatis多条件多值批量更新,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
MySQL并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。
这里使用了case when@H_512_5@
这个小技巧来实现批量更新。
举个例子:
UPDATE 表名 SET display_order = CASE id WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 5 ENDWHERE id IN (1,2,3)
这句SQL的意思是,更新display_order 字段: 如果id=1 则display_order 的值为3, 如果id=2 则 display_order 的值为4, 如果id=3 则 display_order 的值为5。即是将条件语句写在了一起。这里的where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。
单个条件批量更新:
<update id="updateBatch" parameterTyPE="java.util.List"> update 表名 <trim PRefix="set" suffixoverrides=","> <trim prefix="status =case" suffix="end,"> <foreach collection="list" ITem="item" index="index"> <if test="item.status !=null "> when id=#{item.id} then #{item.status} </if> </foreach> </trim> </trim> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BigINT} </foreach> </update>
多条件批量更新:
<update id="updateBatch" parameterType="java.util.List"> update 表名 <trim prefix="set" suffixOverrides=","> status= <foreach collection="list" item="item" open="case " close=" end,"> when field2=#{item.field2} and company_id=#{item.field3} then #{item.status} </foreach> create_time = <foreach collection="list" item="item" open="case " close=" end,"> when field2=#{item.field2} and company_id=#{item.field3} then <choose> <when test="item.createTime!=null"> #{item.createTime} </when> <otherwise>now()</otherwise> </choose> </foreach> </trim> WHERE <foreach collection="list" item="item" open="( " separator=") or (" close=" )"> device_num=#{item.field2} and company_id=#{item.field3} </foreach> </update>
以上是脚本宝典为你收集整理的mybatis多条件多值批量更新全部内容,希望文章能够帮你解决mybatis多条件多值批量更新所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。