I was trying a large batch of insert statements recently. It took a long time and found that mysql supports batch mode, so I did a test with batch mode.
Test1:
@Test
public void testSingleService() {
try {
for (int i = 0; i < 10000; i++) {
iLostProductService.insertProduct(new Product("testSingleService" + i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
mybatis.xml
<sql id = "baseSql">
product_name
</sql>
<insert id="insertProduct" parameterType="com.team.lof.model.Product">
insert into product (<include refid="baseSql"></include>) values (#{name})
</insert>
It takes a very long time, i give up this way.
Test2:
@Test
public void testBatchService() {
List<Product> productList = new ArrayList<Product>();
for (int i = 0; i < 10000; i++) {
productList.add(new Product("2227testBatchService" + i));
}
try {
iLostProductService.insertProductList(productList);
} catch (Exception e) {
e.printStackTrace();
}
}
mybatis.xml
<insert id="insertProductList">
insert into product (<include refid="baseSql"></include>) values
<foreach collection="productList" item="product" separator=",">
(#{product.name})
</foreach>
</insert>
It takes 1s 329ms, pretty fast.
Test3:
Turn on batch mode, spring.datasource.url needs to configure rewriteBatchedStatements=true
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lof?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT&rewriteBatchedStatements=true
@Test
public void testBatchExcutorService() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ProductDao batchProductDao = sqlSession.getMapper(ProductDao.class);
for (int i = 0; i < 10000; i++) {
batchProductDao.insertProduct(new Product("2047testBatchExcutorService" + i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.commit();
sqlSession.close();
}
}
mybatis.xml
<insert id="insertProduct" parameterType="com.team.lof.model.Product">
insert into product (<include refid="baseSql"></include>) values (#{name})
</insert>
It takes 1s 119ms, fastest.
I captured and analyzed the packets separately. The size of each packet in test 1 is 151 bytes, and the size of each packet in test 2 and test 3 is 1466 bytes. Test 2 sent a total of 634 packets with a total size of 575925 bytes. 3 A total of 452 packets were sent with a total size of 392,882 bytes. I checked the packet data of test 2 and test 3 with a size of 1466 bytes, and found that the packet of test 3 was compressed. Is this the reason for the fast batch mode?