mybatis动态sql中批量指定更新的使用
mybatis动态sql中批量指定更新的使用
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
/**
* 批量更新
* 根据id更新字段
*/
void updateBatch(List<Student> list);
}
对应的xml
<update id="updateBatch">
UPDATE STUDENT
<trim prefix="SET" suffixOverrides=",">
<trim prefix="NAME = CASE" suffix="END,">
<foreach collection="list" item="item" index="index">
<if test="item.name!=null and item.name!=''">
when ID=#{item.id} then #{item.name}
</if>
</foreach>
</trim>
<trim prefix="SEX = CASE" suffix="END,">
<foreach collection="list" item="item" index="index">
<if test="item.sex!=null and item.sex!=''">
when ID=#{item.id} then #{item.sex}
</if>
</foreach>
</trim>
<trim prefix="AGE = CASE" suffix="END,">
<foreach collection="list" item="item" index="index">
<if test="item.age!=null">
when ID=#{item.id} then #{item.age}
</if>
</foreach>
</trim>
</trim>
WHERE
<foreach collection="list" item="item" index="index" separator="or">
ID=#{item.id}
</foreach>
</update>
对应测试
@Test
public void updateBatch() {
List<Student> list = new ArrayList<Student>();
list.add(new Student(1,"小明","男",18));
list.add(new Student(2,"小华","女",17));
list.add(new Student(3,"小红","女",17));
studentMapper.updateBatch(list);
}
生成对应sql
UPDATE STUDENT
SET
NAME = CASE
WHEN ID = 1 THEN '小明'
WHEN ID = 2 THEN '小华'
WHEN ID = 3 THEN '小红'
END,
SEX = CASE
WHEN ID = 1 THEN '男'
WHEN ID = 2 THEN '女'
WHEN ID = 3 THEN '女'
END,
AGE = CASE
WHEN ID = 1 THEN 18
WHEN ID = 2 THEN 17
WHEN ID = 3 THEN 17
END
WHERE
ID = 1 OR ID = 2 OR ID =3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现