mysql 批处理模式 测试 1:测试 2:测试 3:

问题描述

我最近尝试了大量的插入语句。找了半天,发现MysqL支持批处理模式,所以用批处理模式做了一个测试。

测试 1:

    @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>

这需要很长时间,我放弃了。

测试 2:

    @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>

需要 1s 329ms,相当快。

测试 3:

开启批处理模式,spring.datasource.url需要配置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>

最快需要 1s 119ms。

我分别捕获并分析了数据包。测试 1 中每个数据包的大小为 151 字节,测试 2 和测试 3 中每个数据包的大小为 1466 字节。测试 2 总共发送了 634 个数据包,总大小为 575925 字节。 3 总共发送了 452 个数据包,总大小为 392,882 字节。我查看了test 2和test 3的包数据,大小为1466字节,发现test 3的包被压缩了。这是快速批处理模式的原因吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...