說明
在開發(fā)的過程中,有時候想要批量 update 數(shù)據(jù)庫中的一批數(shù)據(jù),有很多種方案,常見有手動提交事務(wù)、手動編寫批量更新的 SQL 語句。
下面說明一下使用手動編寫拼接 SQL 語句的方式。
例如:example 表中有下面這些字段。
id(主鍵)、update_time、name、age
java 中定義的實例類
private Long id;
private Date updateTime;
private String name;
private Integer age;
Mapper 中定義的 SQL 批量更新語句
@Update(" <script>" +
" UPDATE example" +
" SET" +
" update_time=CASE id" +
" <foreach collection=\"list\" item=\"item\" index=\"index\">" +
" <choose>" +
" <when test='item.updateTime!=null'>" +
" WHEN ${item.id} THEN #{item.updateTime}" +
" </when>" +
" <otherwise>" +
" WHEN ${item.id} THEN #{item.update_time}" +
" </otherwise>" +
" </choose>" +
" </foreach>" +
" END" +
" ,name= CASE id" +
" <foreach collection=\"list\" item=\"item\" index=\"index\">" +
" <choose>" +
" <when test='item.name!=null'>" +
" WHEN ${item.docId} THEN #{item.name}" +
" </when>" +
" <otherwise>" +
" WHEN ${item.docId} THEN name" +
" </otherwise>" +
" </choose>" +
" </foreach>" +
" END" +
" ,execute_id = CASE id" +
" <foreach collection=\"list\" item=\"item\" index=\"index\">" +
" <choose>" +
" <when test='item.age!=null'>" +
" WHEN ${item.id} THEN #{item.age}" +
" </when>" +
" <otherwise>" +
" WHEN ${item.age} THEN age" +
" </otherwise>" +
" </choose>" +
" </foreach>" +
" END" +
" WHERE doc_id IN " +
" <foreach collection = 'list' item='item' open='(' close=')' separator=',' > " +
" ${item.id}" +
" </foreach>" +
" </script>")
void updateDataBatch(
@Param(value = "list") List<UserEntity> userList);
注意點
該更新語句會更新 where 條件中的所有符合條件的行。
如果使用下面的寫法
" update_time=CASE id" +
" <foreach collection=\"list\" item=\"item\" index=\"index\">" +
" <if test='item.updateTime!=null'>" +
" WHEN ${item.id} THEN #{item.updateTime}" +
" </if>" +
" </foreach>" +
" END" +
則匹配到對應(yīng) id 的數(shù)據(jù)會更新 updateTime 字段,其他符合 where 條件的行中的 updateTime 字段都會置為 NULL。
如果想要實現(xiàn):
只要某個字段指定了 CASE WHEN 語句,那么符合 WHERE 條件的行,都要指定該字段對應(yīng)的值,如果不賦新值,就使用舊值。
可以使用上面Mapper 中定義的 SQL 批量更新語句的寫法。
也可以使用下面的寫法:
" update_time=CASE id" +
" WHEN ${item.id} THEN #{item.updateTime}" +
" else" +
" now()" +
" END" +
針對符合 where 條件中的數(shù)據(jù)行中,指定 id 的行的 updateTime 設(shè)置為指定值,其他行設(shè)置為當(dāng)前時間。