MyBatis 使用 foreach 遍历集合删除数据 - 示例与代码
以下是一个使用 MyBatis 的 foreach 遍历集合进行删除数据的示例代码。假设要删除的记录的 techId、tenantId 和 deviceId 分别为 1、2 和 3。
public void deleteRecords(List<Integer> ids, int techId, int tenantId, int deviceId) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
MybatisMapper mybatisMapper = sqlSession.getMapper(MybatisMapper.class);
// 使用foreach遍历集合,删除符合条件的记录
mybatisMapper.deleteRecordsByCriteria(ids, techId, tenantId, deviceId);
sqlSession.commit();
}
}
MybatisMapper 接口中应该定义一个 deleteRecordsByCriteria 方法,如下:
public interface MybatisMapper {
void deleteRecordsByCriteria(@Param("ids") List<Integer> ids, @Param("techId") int techId,
@Param("tenantId") int tenantId, @Param("deviceId") int deviceId);
}
在对应的 Mapper XML 文件中,可以使用 foreach 标签来遍历 ids 集合,并使用 if 标签判断符合条件的记录:
<delete id="deleteRecordsByCriteria">
delete from my_table
where techId = #{techId} and tenantId = #{tenantId} and deviceId = #{deviceId}
<if test="ids != null and ids.size() > 0">
and id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</delete>
这样,就可以实现使用 foreach 遍历集合,根据指定条件删除符合条件的数据的功能。
原文地址: https://www.cveoy.top/t/topic/nIrS 著作权归作者所有。请勿转载和采集!