Mybatis批量插入或更新

2021-09-19 03:42:10 字數 2124 閱讀 1931

1 更新單條記錄

update course set name = 『course1』 whereid = 『id1』;

2 更新多條記錄的同乙個欄位為同乙個值

update course set name=『course1』 where id in(『id1』,『id2』,'id3);

3 更新多條記錄為多個欄位為不同的值

比較普通的寫法,是通過迴圈,依次執行update語句。

mybatis寫法如下:

update course name=$ where id = $ 一條記錄update一次,效能比較差,容易造成阻塞。

mysql沒有提供直接的方法來實現批量更新,但可以使用case when語法來實現這個功能。

update course

set name = case id

when 1 then 『name1』

when 2 then 『name2』

when 3 then 『name3』

end,

title = case id

when 1 then 『new title 1』

when 2 then 『new title 2』

when 3 then 『new title 3』

endwhere id in (1,2,3)

這條sql的意思是,如果id為1,則name的值為name1,title的值為new title1;依此類推。

在mybatis中的配置則如下:

update course

when id=# then #

when id=# then #

where

id=#

屬性說明

1.prefix,suffix 表示在trim標籤包裹的部分的前面或者後面新增內容

2.如果同時有prefixoverrides,suffixoverrides 表示會用prefix,suffix覆蓋overrides中的內容。

3.如果只有prefixoverrides,suffixoverrides 表示刪除開頭的或結尾的***overides指定的內容。

4 sql批量更新

看另外乙個示例:

update mydata_table 

set status=

when # then #

where id in

#

其中when...then...是sql中的"switch" 語法。這裡借助mybatis的語法來拼湊成了批量更新的sql,上面的意思就是批量更新id在updatebatch引數所傳遞list中的資料的status欄位。還可以使用實現同樣的功能,**如下:
update mydata_table

when id=# then #

where id in

#

其結構如下:

update mydata_table

set status =

case

when id = # then #//此處應該是展開值

…end

where id in (…);

如果對要更新的資料進行判斷,只有符合條件的資料才能進行更新,這種情況可以這麼做:

when id=# then #

這樣的話只有要更新的list中status != null && status != -1的資料才能進行status更新.其他的將使用預設值更新,而不會保持原資料不變.如果要保持原資料不變呢?即滿足條件的更新,不滿足條件的保持原資料不變,簡單的來做就是再加乙個,因為mybatis中沒有if…else…語法,但可以通過多個實現同樣的效果,如下:

when id=# then #

when id=# then mydata_table.status //這裡就是原資料

整體批量更新的寫法如下:

update mydata_table

when id=# then #

when id=# then mydata_table.status//原資料

where id in

#

mybatis批量插入,批量更新

insert into t ingco trade lithium electric product product no,li e product no,transpor report number,msds,transpor report number path,msds path,un tes...

Mybatis批量插入或更新 根據指定字段更新

mybatis批量更新運用on duplicate key update 如果記錄不存在則插入,存在則更新。那麼這個記錄是否存在根據什麼判斷?規則如下 如果你插入的記錄導致unique索引重複,則認為這條記錄存在。比如我建立表的時候設定的唯一索引為字段email,那麼如果email重複時則執行更新,...

mybatis 批量插入 ,更新總結

以下是在專案中運用到 的運用mybatis 批量 更新,插入的方法 注意 1 在程式中封裝了乙個list集合物件,然後需要把該集合中的實體插入到資料庫中 所以,該配置中 傳遞的引數型別 parametertype 為list foreach的主要用在構建in條件中,它可以在sql語句中進行迭代乙個集...