Video in progress

Strong Middle 🌱 Spring

Why is saving 100,000 rows with saveAll so slow, and how do you speed it up?

By default every row becomes its own INSERT, an IDENTITY id turns batching off completely, and the persistence context holds every object in memory and slows down dirty checking. The fix: JDBC batching, a SEQUENCE id, flush/clear in chunks, or plain JDBC.

📖 Answer

Settings:

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

ID strategy:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_seq")
@SequenceGenerator(name = "product_seq", sequenceName = "product_seq", allocationSize = 50)
private Long id;

With IDENTITY, Hibernate has to fetch the id from the database after each INSERT, so it can't batch. allocationSize = 50 gets 50 ids in a single sequence call.

Writing in chunks:

@Transactional
public void importAll(List<ProductRow> rows) {
    for (int i = 0; i < rows.size(); i++) {
        em.persist(toEntity(rows.get(i)));
        if (i % 50 == 49) { em.flush(); em.clear(); } // memory doesn't grow
    }
}

On PostgreSQL, if you add reWriteBatchedInserts=true to the JDBC URL, the driver sends the batch as one multi-row INSERT, which is several times faster again.

For a really big import, bypass JPA entirely: JdbcTemplate.batchUpdate or PostgreSQL COPY. The entity lifecycle only gets in the way here.

How you know it's working: the generate_statistics=true log should show "executing N JDBC batches".