1、foreach写法
注意⚠️
foreach需要在db链接url后面带一个参数&allowMultiQueries=true
举个例子:
url: jdbc:mysql://127.0.0.1:3306/my_tb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
&serverTimezone=GMT%2B8&useSSL=false
这种写法
适用于批量修改为同一种状态
/**
* 根据学生状态批量修改学生们的课程情况
*
* @param courseInfo 课程情况
* @param studenMark 学业情况
* @param list 学生id列表
* @param studentStatus 学生状态
*/
void batchUpStuInfo(@Param("courseInfo") String courseInfo, @Param("studenMark") String studenMark, @Param("list") List<Long> list, @Param("studentStatus") Integer studentStatus);
<update id="batchUpStuInfo">
update student_info
set course_info = #{courseInfo},
student_mark = #{studenMark}
where `student_status` = #{studentStatus}
and `id` in
<foreach collection="list" close=")" open="(" separator="," item="item">
#{item}
</foreach>
</update>
2、case when 写法
适用于对象值不同进行批量修改
/**
* 批量修改学生情况
*
* @param list 学生实体信息列表
*/
void batchUpStuInfo(@Param("list") List<StuPO> list);
<update id="batchUpStuInfo">
update student_info
<set>
<trim prefix="course_info = case" suffix="end,">
<foreach collection="list" item="item">
<if test="item.courseInfo != null">
when id=#{item.id} then #{item.courseInfo}
</if>
<if test="item.courseInfo == null">
when id=#{item.id} then course_info -- 若传入的属性为null,则保持数据库原值
</if>
</foreach>
</trim>
<trim prefix="student_mark = case" suffix="end,">
<foreach collection="list" item="item">
<if test="item.studentMark != null">
when id=#{item.id} then #{item.studentMark}
</if>
<if test="item.studentMark == null">
when id=#{item.id} then student_mark
</if>
</foreach>
</trim>
</set>
where `id` in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
3、效率问题
-
很明显,foreach循环体效率要高很多,因为它仅有一个循环体,第二种虽然最后只会有一条更新语句,但是xml中的循环体有点多,每一个case when 都要循环一遍list集合,所以大批量拼sql的时候会比较慢。
-
但是这两种方式,数据量大之后都会导致SQL阻塞,建议分批进行执行。
推荐 分批工具类链接