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字段:

  1. 如果id=1,則status更新為3;
  2. 如果id=2,則status更新為4;
  3. 如果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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM