using foreach to do batch insert with mybatis

前端 未结 3 991
南方客
南方客 2021-01-03 15:16

I am using mybatis and i would like to insert an ArrayList to some table.
all right using foreach in mapper, well this ends up with oracle exception ORA_00933 .
t

3条回答
  •  甜味超标
    2021-01-03 15:52

    Insert inside Mybatis foreach is not batch, this is a single (could become giant) SQL statement and that brings drawbacks:

    • some database such as Oracle here does not support.
    • in relevant cases: there will be a large number of records to insert and the database configured limit (by default around 2000 parameters per statement) will be hit, and eventually possibly DB stack error if the statement itself become too large.

    Iteration over the collection must not be done in the mybatis XML. Just execute a simple Insert statement in a Java Foreach loop. The most important thing is the session Executor type.

    SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);
    for (Model model : list) {
        session.insert("insertStatement", model);
    }
    session.flushStatements();
    

    I event think that here it will be enough to use ExecutorType.REUSE without flushing statements.

    Unlike default ExecutorType.SIMPLE, the statement will be prepared once and executed for each record to insert.

提交回复
热议问题