Video in progress

Strong Junior 🐻 Hibernate and JPA

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:

  1. The id strategy. With IDENTITY there are no batch inserts. Switch to SEQUENCE (with allocationSize) or a UUID generated in the application.
  2. Mixed entities. If a loop saves an Order, then an OrderItem, then an Order again, the batch is cut every time the type switches. order_inserts groups them by type.
  3. How you're checking. The org.hibernate.SQL log 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.
  4. On MySQL, for the driver to turn a batch into a single multi-row INSERT, you need rewriteBatchedStatements=true in 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.