cpc引流做網(wǎng)站cpa推廣網(wǎng)站策劃書案例
SpringBoot中六種批量更新Mysql 方式效率對比
先上結(jié)論吧,有空可以自測一下,數(shù)據(jù)量大時運行一次還時挺耗時的
效率比較
小數(shù)據(jù)量時6中批量更新效率不太明顯,根據(jù)項目選擇合適的即可,以1萬條為準做個效率比較,效率從高到低一次排名如下
replace into
和ON DUPLICATE KEY
效率最高mybatis-plus
有取巧嫌疑,因為是分批批量更新,其他幾種都是一次更新- for循環(huán)憑借sql和JdbcTemplate相近,即使5萬條,10萬條效率也相近
- case when
然而有時候我們只能選擇case when,因為replace into
和ON DUPLICATE KEY
公司不一定讓用,項目也不一定引入mybatis-plus,數(shù)據(jù)庫url中也不一定有allowMultiQueries=true參數(shù),算是一個兜底方案吧,不管用那種方式大數(shù)據(jù)量時都需要考慮分批
測試結(jié)構(gòu)
環(huán)境信息:mysql-8.0.35-winx64,本地win 10
依次為測試次數(shù)-平均耗時-最小耗時-最大耗時,單位為毫秒
數(shù)據(jù)量 | for | case when | replace into | ON DUPLICATE KEY | mybatis-plus | JdbcTemplate |
---|---|---|---|---|---|---|
500 | 100-61-41-1202 | 100-66-57-426 | 100-16-10-282 | 100-15-10-293 | 100-73-52-564 | 100-87-59-1449 |
1000 | 100-131-94-2018 | 100-241-219-675 | 100-28-18-376 | 100-25-17-331 | 100-117-98-599 | 100-188-136-2397 |
5000 | 100-852-735-8297 | 100-11219-10365-13496 | 100-95-83-569 | 100-93-82-552 | 100-618-517-1415 | 100-1161-911-9334 |
10000 | 10-3957-2370-17304 | 10-45537-44465-48119 | 100-191-171-762 | 100-188-169-772 | 100-1309-1085-5021 | 100-3671-2563-31112 |
50000 | 10-50106-34568-130651 | 卡死不動 | 100-1026-919-1868 | 100-1062-945-1934 | 100-8062-6711-20841 | 100-48744-35482-191011 |
100000 | 10-160170-106223-264434 | 卡死不動 | 10-2551-2292-3688 | 10-2503-2173-3579 | 100-17205-14436-24881 | 10-169771-110522-343278 |
總結(jié)
-
sql語句for循環(huán)效率其實相當高的,因為它僅僅有一個循環(huán)體,只不過最后update語句比較多,量大了就有可能造成sql阻塞,同時在mysql的url上需要加上allowMultiQueries=true參數(shù),即 jdbc:mysql://localhost:3306/mysqlTest?characterEncoding=utf-8&allowMultiQueries=true(公司項目不一定加,我們也不一定有權(quán)限加)。
-
case when雖然最后只會有一條更新語句,但是xml中的循環(huán)體有點多,每一個case when 都要循環(huán)一遍list集合,所以大批量拼sql的時候會比較慢,所以效率問題嚴重。使用的時候建議分批插入(我們公司一直用的就是這種,但是必須分批)。
-
duplicate key update可以看出來是最快的,但是公司一般都禁止使用replace into和INSERT INTO … ON DUPLICATE KEY UPDATE,這種sql有可能會造成數(shù)據(jù)丟失和主從上表的自增id值不一致。而且用這個更新時,記得一定要加上id,而且values()括號里面放的是數(shù)據(jù)庫字段,不是java對象的屬性字段
-
根據(jù)效率,安全方面綜合考慮,選擇適合的很重要。
數(shù)據(jù)庫
CREATE TABLE `people` (`id` bigint(8) NOT NULL AUTO_INCREMENT,`first_name` varchar(50) NOT NULL DEFAULT '',`last_name` varchar(50) NOT NULL DEFAULT '',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
初始化測試數(shù)據(jù)
//初始化10w數(shù)據(jù)
@Test
void init10wData() {for (int i = 0; i < 100000; i++) {People people = new People();people.setFirstName(UUID.randomUUID().toString());people.setLastName(UUID.randomUUID().toString());peopleDAO.insert(people);}
}
批量修改方案
第一種 for
<!-- 批量更新第一種方法,通過接收傳進來的參數(shù)list進行循環(huán)組裝sql -->
<update id="updateBatch" parameterType="java.util.List"><foreach collection="list" item="item" index="index" open="" close="" separator=";">update people<set><if test="item.firstName != null">first_name = #{item.firstName,jdbcType=VARCHAR},</if><if test="item.lastName != null">last_name = #{item.lastName,jdbcType=VARCHAR},</if></set>where id = #{item.id,jdbcType=BIGINT}</foreach>
</update>
第二種 case when
<!-- 批量更新第二種方法,通過 case when語句變相的進行批量更新 -->
<update id="updateBatch2" parameterType="java.util.List">update people<set><foreach collection="list" item="item"><if test="item.firstName != null">first_name = case when id = #{item.id} then #{item.firstName} else first_name end,</if><if test="item.lastName != null">last_name = case when id = #{item.id} then #{item.lastName} else last_name end,</if></foreach></set>where id in<foreach collection="list" item="item" separator="," open="(" close=")">#{item.id}</foreach>
</update>
第三種 replace into
<!-- 批量更新第三種方法,通過 replace into -->
<update id="updateBatch3" parameterType="java.util.List">replace into people(id,first_name,last_name) values<foreach collection="list" index="index" item="item" separator=",">(#{item.id},#{item.firstName},#{item.lastName})</foreach>
</update>
第四種 ON DUPLICATE KEY UPDATE
<!-- 批量更新第四種方法,通過 duplicate key update -->
<update id="updateBatch4" parameterType="java.util.List">insert into people(id,first_name,last_name) values<foreach collection="list" index="index" item="item" separator=",">(#{item.id},#{item.firstName},#{item.lastName})</foreach>ON DUPLICATE KEY UPDATEid=values(id),first_name=values(first_name),last_name=values(last_name)
</update>
第五種mybatis-plus提供的的批量更新
default boolean updateBatchById(Collection<T> entityList) {return this.updateBatchById(entityList, 1000);
}
boolean updateBatchById(Collection<T> entityList, int batchSize);
mybatis-plus提供的批量更新是分批批量更新,默認每批1000條,可以指定分批的條數(shù),每批執(zhí)行完成后提交一下事務(wù),不加@Transactional可能會出現(xiàn)第一批更新成功了,第二批更新失敗了的情況.
第六種JdbcTemplate提供的批量更新
測試代碼
/*** PeopleDAO繼承基類*/
@Mapper
@Repository
public interface PeopleDAO extends MyBatisBaseDao<People, Long> {void updateBatch(@Param("list") List<People> list);void updateBatch2(List<People> list);void updateBatch3(List<People> list);void updateBatch4(List<People> list);
}
@SpringBootTest
class PeopleMapperTest {@ResourcePeopleMapper peopleMapper;@ResourcePeopleService peopleService;@ResourceJdbcTemplate jdbcTemplate;@Testvoid init10wData() {for (int i = 0; i < 100000; i++) {People people = new People();people.setFirstName(UUID.randomUUID().toString());people.setLastName(UUID.randomUUID().toString());peopleMapper.insert(people);}}@Testvoid updateBatch() {List<People> list = new ArrayList();int loop = 100;int count = 5000;Long maxCost = 0L;//最長耗時Long minCost = Long.valueOf(Integer.MAX_VALUE);//最短耗時for (int j = 0; j < count; j++) {People people = new People();people.setId(ThreadLocalRandom.current().nextInt(0, 100000));people.setFirstName(UUID.randomUUID().toString());people.setLastName(UUID.randomUUID().toString());list.add(people);}Long startTime = System.currentTimeMillis();for (int i = 0; i < loop; i++) {Long curStartTime = System.currentTimeMillis();// peopleMapper.updateBatch4(list);// peopleService.updateBatchById(list);jdbcTemplateBatchUpdate(list);Long curCostTime = System.currentTimeMillis() - curStartTime;if (maxCost < curCostTime) {maxCost = curCostTime;}if (minCost > curCostTime) {minCost = curCostTime;}}System.out.println(loop + "-" + (System.currentTimeMillis() - startTime) / loop + "-" + minCost + "-" + maxCost );}private void jdbcTemplateBatchUpdate (List<People> list){String sql = "update people set first_name=?,last_name=? where id = ?";List<Object[]> params = list.stream().map(item -> new Object[]{item.getFirstName(), item.getLastName(), item.getId()}).collect(Collectors.toList());jdbcTemplate.batchUpdate(sql,params);}
}
參考文章:
mybatis批量更新數(shù)據(jù)三種方法效率對比 https://blog.csdn.net/q957967519/article/details/88669552
MySql中4種批量更新的方法 https://blog.csdn.net/weixin_42290280/article/details/89384741
Mysql 批量修改四種方式效率對比(一)https://blog.csdn.net/zk673820543/article/details/106579809/