Using Mybatis 3.4.6 for Oracle Batch-Update and Got the “-1” result

前端 未结 1 804
囚心锁ツ
囚心锁ツ 2020-12-20 06:25

My code like this:


    

        
相关标签:
1条回答
  • 2020-12-20 06:33

    That is not a batch operation.
    It's trying to execute multiple statements with a single PreparedStatement#execute() call and Oracle's JDBC driver does not support it (correction: the driver supports it).
    The correct way is to perform a real batch operation.

    The mapper statement contains a plain UPDATE statement.

    <update id="biz-update">
      update biz_tbl
      set freeze_amount = nvl(freeze_amount,0) + #{payAmount}
      where id = #{cardId}
    </update>
    

    The below code executes batch operation.

    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
    try {
      for (YourItem item : list) {
        sqlSession.update("biz-update", item);
      }
      List<BatchResult> results = sqlSession.flushStatements();
      int totalNumberOfAffectedRows = Arrays.stream(results.get(0).getUpdateCounts()).sum();
      sqlSession.commit();
    } finally {
      sqlSession.close();
    }
    
    • sqlSession#flushStatements() returns a list of BatchResult. In this case, there is only one statement in the batch, so the list size is 1. If you execute multiple statements (e.g. update table A, then insert into table B), the list may contain multiple BatchResults.
    • BatchResult#getUpdateCounts() returns an int array. The first element (=int) is the number of rows updated by the first UPDATE, the second element is the number of rows updated by the second UPDATE, and so forth.
    • If you are updating many rows, you should flush statements intermittently. Please see this answer for how to control batch size.
    0 讨论(0)
提交回复
热议问题