MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

mybatis 批量删除数据的写法(mybatis批量处理数据)

2025-06-13 13:42 huorong 精选文章 2 ℃ 0 评论

1. 使用foreach标签绑定集合参数:

<delete id="deleteByIds" parameterType="List">
    delete from table_name
    where id in 
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
    </foreach>
</delete>

调用方式:


List<Integer> ids = Arrays.asList(1, 2, 3);
int result = mapper.deleteByIds(ids);

2. 使用where标签绑定条件参数:


<delete id="deleteByCondition" parameterType="map">
   delete from table_name 
   <where> 
       <if test="ids != null"> 
           id in 
           <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
               #{item}
           </foreach>
       </if>
   </where>
</delete>

调用方式:


Map<String, Object> map = new HashMap<>();
map.put("ids", Arrays.asList(1, 2, 3));
int result = mapper.deleteByCondition(map);

这两种方式的原理是使用MyBatis的动态SQL,通过foreach标签把List集合或数组中的每个元素绑定到SQL语句的in条件中,从而实现批量删除。使用这两种方式实现批量删除数据时, MyBatis会将底层的JDBC批量操作优化为一个SQL语句,以提高执行效率。所以,在实际使用中,若是对一张表需要批量删除上千条数据,使用这两种MyBatis的批量删除方式,效率会大大高于调用多次单条删除语句。

Tags:mybatis批量删除

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言