更新数据库的几种方式进行对比
1、Mybatis foreach模式,将单条更新语句拼接成一条语句
模拟插入数据
//初始化数据准备
ArrayList<TradeOrderGoods> tradeOrderGoods = new ArrayList<>();
for (int i = 0; i < rows; i++) {
TradeOrderGoods orderGoods = new TradeOrderGoods();
orderGoods.setTradeId(1629584302914176896L);
orderGoods.setSubTradeId(1629584317753624448L);
orderGoods.setTaxFee(new BigDecimal(1.00));
orderGoods.setTaxRate(new BigDecimal(2.00));
if (YesOrNo.YES.getCode().equals(ifAddMoreFields)){
orderGoods.setAgentSubTradeId(1111L);
orderGoods.setActualSendCount(new BigDecimal(0.00));
orderGoods.setBarcode("fashkljhk");
orderGoods.setBatchSendCount(new BigDecimal(10.00));
orderGoods.setGoodsId(111111L);
orderGoods.setGoodsNo("dsadas123");
orderGoods.setBaseUnitSellCount(new BigDecimal(11.00));
}
tradeOrderGoods.add(orderGoods);
}
2、batch模式更新-获取batch模式的sqlSession,循环执行
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
TradeOrderGoodsDefineMapper mapper = sqlSession.getMapper(TradeOrderGoodsDefineMapper.class);
long start = System.currentTimeMillis();
for (int i = 0; i < forTimes; i++) {
for (TradeOrderGoods tradeOrderGood : tradeOrderGoods) {
mapper.batchUpdateTaxRateAndFee2(tradeOrderGood);
}
}
sqlSession.commit();
long end = System.currentTimeMillis();
底层原理:针对相同SQL,复用prepareStatement,批量提交
3、caseWhen模式,批量更新只用一个语句
4、for循环中单条非batch模式的插入
最终结论
结论输出:foreach中拼接SQL > batch模式速度 > casewhen > for循环中单条更新
压测数据结论 更新行数不同下的对比
1.foreach中拼接SQL(更新100000条2个字段 40.5s)>batch模式for循环速度(58s) >casewhen(内存溢出)>for循环中直接批量更新 (10分钟+)
2.foreach中拼接SQL(更新1000条2个字段 0.366s) >batch模式for循环速度(0.58s)>casewhen(1.63s)>for循环中直接批量更新 (9s)
更新字段数不同下的对比
1.foreach中拼接SQL(更新100000条2个字段 40.5s)>batch模式for循环速度(58s) >casewhen(内存溢出)>for循环中直接批量更新 (10分钟+)
2.foreach中拼接SQL(更新100000条10个字段 58.5s)>batch模式for循环速度(71.1s)