封面:學校夜景
xdm,祝大家節日快樂!!????
今天聽《路過人間》演唱會Live限定版,愛上了一句歌詞,
說來慚愧,人對愛只學會,視死如歸,
1.業務需求
如下:
前臺傳給我一個 documentId和List<UpdateDocumentAnswer> 物件給我,
執行條件:通過這個documentId和List<UpdateDocumentAnswer>中對UpdateDocumentAnswer.id,修改document_answer表的資料,
簡單說:就是希望通過一條update陳述句,根據不同的條件改變多條需要改變的資料,

思考一:
我們先按照我們最簡單的思維思考:
即拆成一句一句執行,for回圈執行多條 update 陳述句,
update document_answer set where document_id=#{documentId} and id=#{answer.id}
這樣寫的話,我們的mapper層接收的引數,應該為:
int patchByDocumentId(@Param("documentId") Long documentId,@Param("answers") UpdateDocumentAnswer answers);
實作是可以實作的,但是因為需要執行多條update陳述句,效率是真的不敢恭維,
如果大家有嘗試過,都會知道,for回圈執行sql陳述句是真的要不得的,一條普通的sql,我們都要優化完再優化,更別說一個方法要執行多條sql陳述句了,
所有就啥勒??

推薦大家使用 百度、Bing、Google進行搜索????
我們想到過這種問題,大概率別人也會遇上的,搜一搜,確實有答案低,
所以我們接著進入思考二吧,??
思考二:
還記得文章前面所說:就是希望通過一條update陳述句,根據不同的條件改變多條需要改變的資料,
我們直接 搜怎么一條update用不同條件修改多條資料勒
就是會搜到一個下面的這樣的sql陳述句,
update 表名 set
列1=
case
when 條件1 then 值1
when 條件2 then 值2 end,
列2=
case
when 條件1 then 值1
when 條件2 then 值2 end,
where 條件
說實話,看到這條陳述句的那一刻,感覺自己又沒有學過mysql了,連crud工程師都算不上(捂臉),
解釋:
我們要 修改列1, 當when 條件1 滿足時,則將 列1 修改為 then 后面跟著的 值1,when 條件2 滿足,則將列1修改為then 后面跟著的值2,
這樣一樣,我們就可以執行多條陳述句了啊,
2.實作
我們將之前的mapper層的介面傳入的引數做一下更改,
int patchByDocumentId(@Param("documentId") Long documentId,@Param("answers") List<UpdateDocumentAnswer> answers);
mapper.xml的實作如下:
<update id="patchByDocumentId">
update document_answer
<set>
<trim prefix="template_question_id = case" suffix="end,">
<foreach collection="answers" item="answer">
<if test="answer.templateQuestionId != null">
when id=#{answer.id} then #{answer.templateQuestionId}
</if>
</foreach>
</trim>
<trim prefix="answer = case" suffix="end,">
<foreach collection="answers" item="answer">
<if test="answer.answer != null">
when id=#{answer.id} then #{answer.answer}
</if>
</foreach>
</trim>
<trim prefix="comments = case" suffix="end,">
<foreach collection="answers" item="answer">
<if test="answer.comments != null">
when id=#{answer.id} then #{answer.comments}
</if>
</foreach>
</trim>
</set>
<where>
document_id=#{documentId}
<if test="answers != null">
and id in
<foreach collection="answers" separator="," item="answer" open="(" close=")">
#{answer.id}
</foreach>
</if>
</where>
</update>
生成的sql日志
update document_answer
SET
template_question_id =
case
when id=? then ?
when id=? then ? end,
answer =
case
when id=? then ?
when id=? then ? end,
comments =
case
when id=? then ?
when id=? then ? end
WHERE document_id=? and id in ( ? , ? )
換上我們想要的值:
update document_answer
SET
template_question_id =
case
when id=1 then 2
when id=1 then 3 end,
answer =
case
when id=1 then '內容1'
when id=2 then '內容2' end,
comments =
case
when id=1 then '評論1'
when id=2 then '評論2' end
WHERE document_id=2 and id in ( 1 , 2 )
執行規則: 上面這種方式,更新的記錄的數量取決于list集合的數量,且每條記錄中的值和對應記錄的ID是一一對應的,
結束了,周日更文一篇,
后語
我們一起加油吧
你好,我是博主
寧在春:主頁希望本篇文章能讓你感到有所識訓!!!
祝
我們:待別日相見時,都已有所成,歡迎大家一起討論問題??,躺了??
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335051.html
標籤:Java
上一篇:超市訂單管理系統(5)-密碼修改
