2017-08-08 97 views
1

任務:我需要至少將10k條記錄插入爲一批。Java,MyBatis 3.4,巨大的批量插入事實上並未實際存儲到DB

實際上:在提交/刷新調用期間,我可以通過使用「SELECT * FROM TABLE」看到記錄是由完全隨機數插入的。 就像它可以插入1k,然後500,然後再插入1.5k,然後再插入500.一些真正奇怪的東西正在進行這個批處理。

我真的有基本的設置,如:

<bean id="armDataSource" 
      class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
     <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/> 
     <property name="jdbcUrl" value="${database.url}"/> 
     <property name="user" value="${database.username}"/> 
     <property name="password" value="${database.password}"/> 
     <property name="maxPoolSize" value="30"/> 
     <property name="idleConnectionTestPeriod" value="300"/> 
     <property name="maxIdleTime" value="300"/> 
     <property name="preferredTestQuery" value="SELECT 1"/> 
     <property name="testConnectionOnCheckin" value="true"/> 
    </bean> 
    <tx:annotation-driven /> 

    <bean id="armTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
     <property name="dataSource" ref="armDataSource"/> 
    </bean> 

    <bean id="armSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
     <property name="dataSource" ref="armDataSource"/> 
     <property name="typeAliasesPackage" value="com.database.arm.model"/> 
    </bean> 

    <bean id="armSqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> 
     <constructor-arg index="0" ref="armSqlSessionFactory" /> 
     <constructor-arg index="1" value="BATCH" /> 
    </bean> 

然後,我有以下代碼:

SqlSession sqlSession = armSqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false); 
     HeaderMapper headerMapper = sqlSession.getMapper(HeaderMapper.class); 
     List<List<HeaderDAO>> partitions = Lists.partition(HeaderDAOS, 10000); 
       partitions.forEach(partition -> { 
        partition.forEach(headerDAO -> { 
         headerDAO.setFileId(fileId); 
         headerMapper.insert(headerDAO); 
        }); 
    sqlSession.flushStatements(); 
    }); 
     sqlSession.commit(); 
     sqlSession.close(); 

它工作得很好用的100個或更少的記錄小批量插入。但是一旦我走得更高,看起來就像mybatis做了更多的一批。

也許有一些問題與sqlSessionFactory或模板或數據源的設置?我嘗試了很多選擇,但都沒有幫助。 任何輸入是非常讚賞。

回答

0

所以我調試了所有的堆棧,直到mysql驅動程序,並找到原因。 默認情況下,MySQL驅動程序實際上是在一個事務中逐個執行批量插入。 要啓用一個大批量插入,你需要讓mysqldriver知道,通過使用屬性:

rewriteBatchedStatements =真

這可以在中的ConnectionURL通過屬性被忽略的數據源,或指定

<property name="properties"> 
    <props> 
     <prop key="rewriteBatchedStatements">true</prop> 
    </props> 
</property> 

PS:數據源的你只需要在MyBatis的情況下使用它,因爲例如,Hibernate會自動執行。

相關問題