Mybatis 实现多条件、多值批量更新
一、SQL CASE WHEN
Oracle、MySql并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。这里使用了case when来实现批量更新。
例如:
1 UPDATE demo_table SET 2 status = CASE id 3 WHEN 1 THEN 3 4 WHEN 2 THEN 4 5 WHEN 3 THEN 5 6 END 7 WHERE id IN (1,2,3)
这个SQL语句的作用是根据条件更新demo_table表的status字段:
- 如果id=1,则status更新为3;
- 如果id=2,则status更新为4;
- 如果id=3,则status更新为5。
即是将条件语句写在了一起,提高SQL执行效率。
二、Mybatis
单个条件字段批量更新:
1 <update id="updateBatch" parameterType="java.util.List"> 2 update demo_table 3 <trim prefix="set" suffixOverrides=","> 4 <trim prefix="status =case" suffix="end,"> 5 <foreach collection="list" item="item" index="index"> 6 <if test="item.status !=null "> 7 when id=#{item.id} then #{item.status} 8 </if> 9 </foreach> 10 </trim> 11 </trim> 12 where id in 13 <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> 14 #{item.id,jdbcType=BIGINT} 15 </foreach> 16 </update>
多个条件字段批量更新:
1 <update id="updateBatch" parameterType="java.util.List"> 2 update CLIENT_INFO 3 <trim prefix="set" suffixOverrides=","> 4 CARD_NUM= 5 <foreach collection="list" item="item" open="case " close=" end,"> 6 when ID_CARD_NO=#{item.idCardNo} and STATUS=4 then #{item.cardNum} 7 </foreach> 8 create_time = 9 <foreach collection="list" item="item" open="case " close=" end,"> 10 when field2=#{item.field2} and field3=#{item.field3} then 11 <choose> 12 <when test="item.createTime!=null"> 13 #{item.createTime} 14 </when> 15 <otherwise>now()</otherwise> 16 </choose> 17 </foreach> 18 </trim> 19 WHERE 20 <foreach collection="list" item="item" open="( " separator=") or (" close=" )"> 21 ID_CARD_NO=#{item.idCardNo} and field3=#{item.field3} 22 </foreach> 23 </update>