删除量:一次删除10000条。
第一种方式,通过delete from 表 where id in(一堆ID)的方式删除数据,首先把需要删除的数据从数据库查询出来,将ID传给mybatis框架,展示如下:
DELETE FROM TBL_ACC_HIS_SOURCE WHERE ID IN #{id}
每次耗时数据如下:
[374, 206, 206, 205, 482, 231, 460, 297, 277, 218, 232, 203, 228, 272, 207, 280, 203, 195, 272, 374, 523, 314, 207, 222, 247, 275, 269, 203, 216, 190, 310, 225, 277, 238, 237, 213, 228, 235, 236, 204, 240, 217, 213, 191, 209, 260, 268, 317, 231, 207, 200, 203, 204, 202, 209, 217, 212, 310, 216, 253, 201, 204, 212, 191, 211, 200, 237, 234, 279, 194, 203, 250, 199, 228, 224, 238, 259, 279, 257, 299, 196, 264, 299, 210, 228, 227, 219, 203, 207, 328, 213, 237, 348, 315, 210, 219, 325, 236, 196, 197, 211, 229, 187, 276]
共执行104次,平均耗时243毫秒。
第二种方式,使用batch delete,代码如下:
private void batchDeleteA(Listids){ SqlSession batchSqlSession = getBatchSession(); try { for (Long id : ids) { batchSqlSession.delete("AccHisSourceEntity.delete", id); } batchSqlSession.commit(); } finally { BatchSqlSessionUtils.closeSqlSession(batchSqlSession); } }
private SqlSession getBatchSession() { return BatchSqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH); }
其中AccHisSourceEntity.delete如下:
delete from TBL_ACC_HIS_SOURCE where ID = #{id,jdbcType=BIGINT}
执行119次,每次耗时如下:
[454, 253, 230, 224, 219, 214, 217, 215, 203, 204, 240, 250, 243, 230, 272, 208, 205, 223, 450, 235, 282, 336, 266, 209, 212, 222, 214, 431, 256, 238, 209, 456, 199, 616, 207, 336, 249, 196, 232, 230, 291, 240, 212, 266, 245, 229, 217, 211, 218, 210, 211, 218, 222, 215, 200, 219, 208, 256, 208, 208, 248, 226, 220, 234, 219, 299, 478, 501, 251, 223, 510, 244, 265, 246, 278, 279, 244, 255, 251, 236, 260, 273, 246, 503, 280, 238, 256, 244, 255, 215, 217, 224, 220, 230, 236, 198, 252, 246, 270, 262, 263, 252, 233, 223, 262, 230, 478, 240, 269, 238, 232, 260, 232, 222, 228, 223, 231, 246, 247]
平均耗时:258
结论:几乎相同。
PS:如果采用查出一批数据,删除一批数据的方式。采用5000一批,比10000一批要快一些。