返回顶部
首页 > 资讯 > 后端开发 > JAVA >Mybatis实现批量删除(两种常用方法)
  • 409
分享到

Mybatis实现批量删除(两种常用方法)

javaspring开发语言 2023-09-16 13:09:44 409人浏览 泡泡鱼
摘要

1.第一种方式:         将任意多个 id 拼接成字符串,以参数形式传递进去,通过 in 函数 的方式来删除         ①首先定义接口类 //通过id所组成的字符串实现批量删除 public void d

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