Hibernate / MyBatis Interview questions
How do you handle batch inserts/updates in MyBatis?
MyBatis supports batch operations two main ways: using the <foreach> element to build a single multi-row SQL statement, or using MyBatis's BATCH executor type to send multiple separate statements to the database together as one batch, reducing round-trip overhead compared to executing each statement individually.
<insert id="batchInsertUsers"> INSERT INTO users (name, email) VALUES <foreach collection="list" item="user" separator=","> (#{user.name}, #{user.email}) </foreach> </insert>
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) { UserMapper mapper = session.getMapper(UserMapper.class); for (User user : users) { mapper.insertUser(user); } session.commit(); }
The <foreach>-based multi-row insert approach works well when the number of rows is moderate and known upfront, producing one large SQL statement in a single round trip; the BATCH executor approach is better suited to a large or dynamically-sized set of individual operations, since it lets the same mapper method be called repeatedly in a loop while MyBatis defers actually sending the statements to the database until commit(), batching them together at the JDBC driver level.
Which approach performs better in practice depends on the specific database and driver, and on operation count — for very large batches, the BATCH executor combined with periodically flushing (committing in smaller sub-batches rather than one enormous batch) is generally the safer, more memory-predictable choice over a single, extremely large multi-row SQL statement.
More Related questions...