Video in progress

What settings do you need to speed up bulk INSERTs in Hibernate?

Turn on hibernate.jdbc.batch_size, group statements with order_inserts/order_updates, use SEQUENCE rather than IDENTITY for the id, and empty the persistence context with flush() + clear() every N records.

📖 Answer

The settings:

spring:
  jpa:
    properties:
      hibernate:
        jdbc.batch_size: 50
        order_inserts: true
        order_updates: true

Why order_inserts: in a sequence like Order, Item, Order, Item, the batch breaks every time the type switches. Sorting puts the same INSERTs next to each other.

The code side:

@Transactional
public void importAll(List<ProductRow> rows) {
    for (int i = 0; i < rows.size(); i++) {
        em.persist(toEntity(rows.get(i)));
        if (i > 0 && i % 50 == 0) {
            em.flush();
            em.clear(); // otherwise 100k entities and their snapshots stay in memory
        }
    }
}

Things to check:

  • If the id strategy is IDENTITY, batching doesn't work, so sort that out first.
  • If you add reWriteBatchedInserts=true to the PostgreSQL JDBC driver, the batch turns into a single multi-row INSERT and gets even faster. On MySQL the equivalent is rewriteBatchedStatements=true.
  • Check that batching is really working with the "executing N JDBC batches" line in generate_statistics, or with datasource-proxy. show-sql doesn't help here, because it shows every statement separately.

With hundreds of thousands of rows, an ORM is heavy anyway. I often do such imports with JdbcTemplate.batchUpdate or PostgreSQL COPY.