Mybatis 中传入List实现 批量插入、批量更新、批量删除

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

那么就需要修改这个设置项,所以推荐提前先把对应的设置值稍微弄大一点

posted @   chelsey3tsf  阅读(3899)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示