Mybatis 中传入List实现 批量插入、批量更新、批量删除
2024-10-08 07:29:12
1. 批量插入:
Mapper层:
int insertList(List<UsersModel> list);
对应的mapper.xml:
<!--批量插入信息-->
<insert id="insertList" parameterType="java.util.List">
insert into users(
id, name
)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}
)
</foreach>
</insert>
如果List数据量比较大,可以考虑将List分批次插入
2. 批量更新:
批量更新只提供更新单个字段的,因为更新多个字段无论哪种批量更新方案,我都用起来很不舒服,所以不做提供。
Mapper层:
int updateList(List<AgentApply> list);
对应的mapper.xml:
<!--批量更新-->
<update id="updateList" parameterType="java.util.List">
update agent_apply
set apply_time=
<foreach collection="list" item="item" index="index"
separator=" " open="case" close="end">
when id=#{item.id} then #{item.applyTime}
</foreach>
where id in
<foreach collection="list" index="index" item="item"
separator="," open="(" close=")">
#{item.id,jdbcType=INTEGER}
</foreach>
</update>
3. 批量删除:
PS:一般查询出来的List都是包含对象在里面的,那么怎么清理出单独包含ID的list呢?
可以参考下面方式,第一个listData是从数据库查询出来的list数据,每个元素都是一个对象;
然后单独把里面每个元素的id给取出来放入新的list(ids)。
List<AgentRechargeOrder> listData = agentRechargeOrderServiceImpl.getListByXXXX(XXXX);
List<Integer> ids = listData.stream().map(AgentRechargeOrder::getId).collect(Collectors.toList());
如果不想清除出单独的id的list,直接传整个List也是可以的, 这样mapper层传值就改成对应的包含对象的List即可。
Mapper层:
int deleteMany(List<Integer> ids);
对应的mapper.xml:
<delete id="deleteMany">
delete from agent_recharge_order where id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
最后补充个提醒:
因为批量操作会拼接成很长很长的mysql语句,所以mysql server在接收数据包的时候,对这个数据包的大小是有设置项限制的。
如果超过设置的值,就会报错:
Caused by: com.mysql.jdbc.PacketTooBigException: Packet for query is too large
那么就需要修改这个设置项,所以推荐提前先把对应的设置值稍微弄大一点
最新文章
- bitnami redmine版本由2.3.1升级至3.2.2过程
- [ios]新手笔记-。-UIPickerView 关于伪造循环效果和延时滚动效果
- #9.5课堂JS总结#循环语句、函数
- 学习 zookeeper
- JqueryDemoTools-用于整理jQueryDemo 分类: C# 公共资源 2014-12-02 16:50 224人阅读 评论(1) 收藏
- 0506--Scrum项目1.0
- VueJs2.0建议学习路线
- AC自动机---病毒侵袭
- 把数据保存到数据库附加表 `dede_addonarticle` 时出错,请把相关信息提交给DedeCms官方。Duplicate entry
- 作业6 NABCD模型分析,产品Backlog
- MongoDB (二) MongoDB 优点
- jQuery遍历DOM
- tcxtreelist Properties的使用(TcxImageComboBoxProperties)
- Android(java)学习笔记258:JNI之hello.c(c代码功能实现)指针语法解析
- Invalid file permission Please regenerate them with cacaoadm create-keys --force
- 贪吃蛇AI
- Redhat
- python爬微信公众号前10篇历史文章(5)-JSON相关内容小结
- python 中is和== 的理解
- 找到IIS 站点对应的站点日志
热门文章
- 小H的小屋
- 全志R528 系统繁忙时触摸屏I2C报错问题。
- 迷宫机器人最短路径使用tkinter绘制
- Hugging Face - 推理(Inference)解决方案
- 图文并茂手把手教你How to copy files or directory in nodejs npm scripts编写脚本用npm或者node命令复制文件
- angular + ng-zorro 表格后台分页及排序功能实现,angular + ng-zorro 表格排序不起作用解决办法
- 多行文字自动换行居中--实测好用的很OK
- OpenMP 线程同步 Construct 实现原理以及源码分析(上)
- 自定义接口-lambda使用前提
- 前端基础知识-react(一)个人学习记录 _