說明:
1.Oracle版本 11g
2.mybatis版本 3.2.3
場景
批量修改數據,但where條件不一樣。
舉例
表名 tableName
要求將字段A的值爲1的數據修改其字段B的值爲“B1”;將字段A的值爲2的數據修改其字段B的值爲“B2”;將字段A的值爲3的數據修改其字段B的值爲“B3”
實現
一、對此可以寫3條update語句來實現需求
update tableName set B = 'B1' where A = '1'
update tableName set B = 'B2' where A = '2'
update tableName set B = 'B3' where A = '3'
二、對多條update語句進行合併
update tableName set B = (case A
when '1' when 'B1'
when '2' when 'B2'
when '3' when 'B3'
end)
where A in ('1','2','3')
三、mybatis中的Mapper編寫實現
1.定義入參List<T> list = new ArrayList<>()
2.list中添加值(僞代碼)
t1.setA("1");t1.setB("B1");list.add(t1);
t1.setA("2");t1.setB("B2");list.add(t2);
t1.setA("3");t1.setB("B3");list.add(t3);
3.mapper中語句如下:
<update id="updateBatch">
UPDATE tableName
SET
B = (CASE A
<foreach collection="list" index="index" item="item"
open=" " separator=" " close=" ">
WHEN #{item.a} THEN
#{item.b}
</foreach>
END)
where A in
<foreach collection="list" index="index" item="item"
open="(" separator="," close=")">
#{item.a}
</foreach>
</update>