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

个人收藏使用

文章来自Mybatis 中传入List实现 批量插入、批量更新、批量删除 - chelsey3tsf - 博客园 (cnblogs.com)

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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值