Video in progress
You need to write several million rows to the database fast through Hibernate. How do you approach it?
I turn on JDBC batching, use a (pooled) sequence for IDs, flush/clear every N rows, or switch to StatelessSession. At really large volumes, COPY or a native bulk insert is faster still.
📖 Answer
The first thing I check is how IDs are generated. With GenerationType.IDENTITY, Hibernate has to send the INSERT right on each persist, because it needs the ID back from the database. As a result hibernate.jdbc.batch_size does nothing at all. With a sequence and allocationSize=50, Hibernate fetches IDs ahead of time and sends the INSERTs in groups.
spring:
jpa:
properties:
hibernate:
jdbc.batch_size: 100
order_inserts: true
The second problem is memory. The persistence context holds every entity and its snapshot. Once a million objects pile up, dirty checking slows down and the GC struggles.
for (int i = 0; i < rows.size(); i++) {
em.persist(toEntity(rows.get(i)));
if (i % 100 == 0) {
em.flush(); // sends the batch
em.clear(); // empties the context
}
}
The alternative is StatelessSession: no persistence context, no dirty checking, no cascade. That is exactly what an import job needs.
On PostgreSQL, the reWriteBatchedInserts=true driver parameter turns a batch into a single multi-row INSERT, which gives a noticeable speedup too. If we are talking tens of millions of rows, I set the ORM aside and use COPY or JdbcTemplate.batchUpdate: Hibernate adds nothing here.
Sign up to mark studied questions and save your progress.