一、方式
update table_name set db_filed_name='涨三' where sys_id=1 and sys_name='系统名称'
//对以上sql进行批量更新批量执行
@Update("<script>" +
" update user_info" +
"<trim prefix='set' suffixOverrides=','>" +
" user_code=" +
"<foreach collection='list' item='item' open='case ' close=' end,'>" +
" when user_id=#{item.userId} and user_name=#{item.userName} then
#{item.userCode}" +
"</foreach>" +
"</trim>" +
" WHERE" +
"<foreach collection='list' item='item' open='( ' separator=') or ('close=' )'>" +
" user_id=#{item.userId} and user_name=#{item.userName}" +
" </foreach>" +
"</script>")
Integer updateUser(List<UserInfoDto> list);
二、解析
1.待更新的数据集是List<User>,其中我们根据User中的userId和userName字段修改user_code 值
2.可以采用动态sql的方式进行批量更新,由于我们采用了动态sql的标签<foreach>,所以需要在sql左外层填加<script></script>进行包裹;
3.这里采用<foreach>进行list遍历。collection 表示集合名;item表示给集合取的别名;open/close表示sql以某个字段开始/结束,我们这边不需要,所以什么都没写;separator表示以什么符号进行分隔。
4.以上动态sql组装完成之后会以以下sql一次性执行:
update table_name set user_code='涨三' where user_id=1 and user_name='系统名称1'; update table_name set user_code='里斯' where user_id=2 and user_name='系统名称2'; update table_name set user_code='王五' where user_id=3 and user_name='系统名称3'; update table_name set user_code='找钱' where user_id=4 and user_name='系统名称4'; update table_name set user_code='孙俪' where user_id=5 and user_name='系统名称5'; update table_name set user_code='签章' where user_id=6 and user_name='系统名称6' .......