Mybatis实现批量删除(两种常用方法)
短信预约 -IT技能 免费直播动态提醒
1.第一种方式:
将任意多个 id 拼接成字符串,以参数形式传递进去,通过 in 函数 的方式来删除
①首先定义接口类
//通过id所组成的字符串实现批量删除 public void deleteId(@Param("ids") String ids);
②在实现类中配置Mapper.xml
delete from accounts where id in (${ids})
③测试类
@Test public void testDeleteIds() { ad.deleteId("25,26,27"); sqlSession.commit(); MyBatisUtil.close(sqlSession); }
④结果
DEBUG [main] - Logging initialized using 'org.apache.ibatis.logging.log4j.Log4jImpl' adapter.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - Openning JDBC ConnectionDEBUG [main] - Created connection 331510866.DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@13c27452]DEBUG [main] - ==> Preparing: delete from accounts where id in (25,26,27) DEBUG [main] - ==> Parameters: DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]DEBUG [main] - Returned connection 331510866 to pool.
注意: #{}中字符串类型会使用单引号,${} 则无需。这里只能使用${}方式,不能使用#{}
2.第二种方式如下:
使用 foreach 标签来进行删除
①首先定义接口类
// 通过list集合实现批量删除 public void deleteByIds(@Param("ids") List ids);
②在实现类中配置Mapper.xml
③测试类
@Test public void testDeleteByIds() throws IOException { List List = new ArrayList<>(); List.add(22); List.add(23); List.add(24); ad.deleteByIds(List); sqlSession.commit(); MyBatisUtil.close(sqlSession); }
④结果
DEBUG [main] - Logging initialized using 'org.apache.ibatis.logging.log4j.Log4jImpl' adapter.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - Openning JDBC ConnectionDEBUG [main] - Created connection 249155636.DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@ed9d034]DEBUG [main] - ==> Preparing: delete from accounts where id in ( ? , ? , ? ) DEBUG [main] - ==> Parameters: 28(Integer), 29(Integer), 30(Integer)DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@ed9d034]DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@ed9d034]DEBUG [main] - Returned connection 249155636 to pool.
总结:两种方式均可,可根据自身熟悉度进行选择
来源地址:https://blog.csdn.net/qq_35260388/article/details/126853562
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341