Mybatis 批量添加,批量更新
此篇适合有一定的mybatis使用经验的人阅读.
一.批量更新
为了提升操作数据的效率,第一想到的是做批量操作,直接上批量更新代码:
1 <update id="updateBatchMembers" parameterType="list"> 2 update crm_member 3 <trim prefix="set" suffixOverrides=","> 4 <trim prefix="dept_id =case" suffix="end,"> 5 <foreach collection="list" item="i" index="index"> 6 <if test="i.deptId!=null"> 7 when id=#{i.id} then #{i.deptId} 8 </if> 9 </foreach> 10 </trim> 11 <trim prefix=" sys_user_id =case" suffix="end,"> 12 <foreach collection="list" item="i" index="index"> 13 <if test="i.sysUserId!=null"> 14 when id=#{i.id} then #{i.sysUserId} 15 </if> 16 </foreach> 17 </trim> 18 19 <trim prefix="public_area_id =case" suffix="end," > 20 <foreach collection="list" item="i" index="index"> 21 <if test="i.publicAreaId!=null"> 22 when id=#{i.id} then #{i.publicAreaId} 23 </if> 24 </foreach> 25 </trim> 26 </trim> 27 where 28 <foreach collection="list" separator="or" item="i" index="index" > 29 id=#{i.id} 30 </foreach> 31 </update>
生成的sql语句
1 update 2 crm_member 3 set 4 dept_id =case 5 when id=? then ? 6 when id=? then ? 7 when id=? then ? 8 when id=? then ? 9 end, 10 sys_user_id =case 11 when id=? then ? 12 when id=? then ? 13 when id=? then ? 14 when id=? then ? 15 end, 16 public_area_id =case 17 when id=? then ? 18 when id=? then ? 19 when id=? then ? 20 when id=? then ? 21 end 22 where 23 id=? 24 or id=? 25 or id=? 26 or id=? 27 or id=?
二.批量添加
批量添加在做大量数据插入到mysql时,效率相对单条遍历插入大大提高;
但是数据是基于数据库层面做的约束的话,在插入的数据中有一个数据有误,整个批量操作全部回滚;
适用场景:数据迁移时使用.
1 <insert id="batchInsertMember" parameterType="java.util.List"> 2 insert into crm_member( 3 id, 4 name, 5 type, 6 phone, 7 link, 8 ) 32 values 33 <foreach collection="list" item="item" index="index" separator=","> 34 ( 35 #{item.id}, 36 #{item.name}, 37 #{item.type}, 38 #{item.phone}, 39 #{item.link} 40 ) 64 </foreach> 65 </insert>
生成对应的sql
1 insert into 2 crm_member3 (
id,
name,
type,
phone,
link
) 4 values 5 (?,?,?,?,?), 6 (?,?,?,?,?), 7 (?,?,?,?,?), 8 (?,?,?,?,?)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!