Video in progress
I set hibernate.jdbc.batch_size, but the INSERTs still go one at a time. What could the cause be?
The most common cause is GenerationType.IDENTITY: to get the id, Hibernate runs every INSERT immediately and separately, which disables batching. Other causes are mixed entity types being saved interleaved (no order_inserts) or checking for batching the wrong way in the logs.
📖 Answer
The right configuration:
spring:
jpa:
properties:
hibernate:
jdbc.batch_size: 50
order_inserts: true
order_updates: true
A checklist:
- The id strategy. With
IDENTITYthere are no batch inserts. Switch toSEQUENCE(withallocationSize) or a UUID generated in the application. - Mixed entities. If a loop saves an
Order, then anOrderItem, then anOrderagain, the batch is cut every time the type switches.order_insertsgroups them by type. - How you're checking. The
org.hibernate.SQLlog prints every INSERT as a separate line regardless, which doesn't mean batching is off. Look at the "executing N JDBC batches" line in the statistics (generate_statistics), or use a tool like datasource-proxy. - On MySQL, for the driver to turn a batch into a single multi-row INSERT, you need
rewriteBatchedStatements=truein the URL.
With big batch loads, don't forget memory either:
for (int i = 0; i < rows.size(); i++) {
em.persist(rows.get(i));
if (i % 50 == 49) { em.flush(); em.clear(); }
}
Otherwise batching works, but hundreds of thousands of objects pile up in the persistence context.
Sign up to mark studied questions and save your progress.