Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A Spring Data JPA saveAll of 100,000 entities is slow although hibernate.jdbc.batch_size=50 is set. The entity uses @GeneratedValue(strategy = GenerationType.IDENTITY). Why, and what would you change?

With GenerationType.IDENTITY, the database assigns the id during the INSERT, and Hibernate needs that id immediately to manage the entity, so it executes every insert on its own and silently disables JDBC insert batching, whatever hibernate.jdbc.batch_size says. We switch to a SEQUENCE generator with an allocationSize such as 50 so ids are known before the inserts, set hibernate.order_inserts=true, flush and clear the persistence context every batch, and verify batching with datasource-proxy or Hibernate statistics. For very large loads, JDBC batching or COPY outside the ORM is faster still.

Background to this question

This problem is a favourite because the configuration looks right and the code looks right, yet 100,000 rows take minutes. The reason sits in how Hibernate tracks entities and how the database generates keys, and it is a good test of whether we verify behaviour instead of trusting settings. In this answer, we will recap how Hibernate batches, see why IDENTITY breaks it, switch to a sequence, fix the memory side of saveAll, verify that batching really happens, and decide when to leave the ORM.

1A Quick Recap of Hibernate Batching

When we persist an entity, Hibernate does not run SQL immediately. It records the entity in the persistence context, the first-level cache of managed entities for the current session, and writes the changes at flush time, usually at commit. With hibernate.jdbc.batch_size=50, it groups up to 50 similar INSERT statements into one JDBC batch, which travels to the database in one exchange instead of 50.

For this to work, Hibernate must be able to delay the INSERT until flush. That is the crucial condition, and it is exactly what IDENTITY takes away.

2Why IDENTITY Disables Batching

With IDENTITY, the id is produced by the database column itself, an identity or serial column in PostgreSQL or AUTO_INCREMENT in MySQL, at the moment the row is inserted. Hibernate identifies each managed entity by its id in the persistence context, so when we call persist, it needs the id right away. The only way to get it is to run the INSERT immediately and read back the generated key. An INSERT that has already been executed cannot be part of a later batch, so Hibernate executes each one on its own.

Java
@Entity
class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
// ...
}
orderRepository.saveAll(orders); // 100,000 orders
// insert into orders (...) values (...) returning id -- executed alone
// insert into orders (...) values (...) returning id -- executed alone
// ... 100,000 round trips, batch_size=50 has no effect on these inserts
Step throughIDENTITY versus SEQUENCE during persist
ApplicationHibernateDatabase
persist(order) with IDENTITY
INSERT now, need the generated id
id = 1001
persist(order) with SEQUENCE, allocationSize 50
nextval once per 50 entities
ids 1051 to 1100 reserved
at flush: one batch of 50 INSERTs

7 messages in order. Play them, or step through them one at a time.

With a sequence, ids are known in advance, so inserts can wait for flush and travel together.

Notice that there is no error and, depending on the version, only a quiet log message at most. The setting is accepted, it simply cannot apply to these inserts. That is why this problem often survives until someone looks at the actual statements.

3Fix 1: Switch to a Sequence With allocationSize

A sequence is a database object that hands out numbers independently of any table. Hibernate can ask it for ids before inserting, so the INSERT can wait until flush and join a batch. With allocationSize = 50, Hibernate's pooled optimizer calls nextval once and assigns 50 ids in memory, so the sequence itself costs one round trip per 50 entities.

Java
@Entity
class Order {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
Long id;
}
-- the database sequence must step by the same amount
CREATE SEQUENCE order_seq INCREMENT BY 50;
# application.properties
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

The sequence's INCREMENT BY must match allocationSize, otherwise Hibernate may assign overlapping or unexpected ids, and recent Hibernate versions check this at startup when schema validation runs. order_inserts=true makes Hibernate group inserts by entity type, which matters when we save orders together with their lines: without it, alternating order and line inserts would break every batch after one statement. For an existing table with an identity column, the migration is a schema change: create the sequence starting above the current maximum id and change the column default, and plan it like any other migration. On MySQL, which has no sequences, application-generated ids such as time-ordered UUIDs are the usual alternative.

4Fix 2: Keep the Persistence Context Small

Even with batching, saveAll of 100,000 entities in one transaction keeps all of them managed in the persistence context. Memory grows, and every flush has to dirty-check all managed entities, so the work per flush grows as the load goes on. We persist in chunks and flush and clear after each one.

Java
@Transactional
public void importOrders(List<Order> orders) {
for (int i = 0; i < orders.size(); i++) {
em.persist(orders.get(i));
if ((i + 1) % 50 == 0) {
em.flush(); // sends one JDBC batch of 50 inserts
em.clear(); // detaches them, so memory stays flat
}
}
}

Notice that the chunk size matches batch_size, so each flush produces exactly one full batch. After clear(), the entities are detached, so the code must not rely on them being managed later in the same transaction. Splitting very large imports into several transactions also keeps locks and undo shorter.

5Verify That Batching Really Happens

The lesson of this problem is that a setting is not proof. We check the statements actually sent. datasource-proxy, a JDBC wrapper, logs each execution with whether it was a batch and its size, and Hibernate statistics report how many JDBC batches were executed.

Text
# with datasource-proxy logging
Name:ds, Batch:True, QuerySize:1, BatchSize:50, Query:["insert into orders (...) values (?,?,?)"]
# with spring.jpa.properties.hibernate.generate_statistics=true
... 2000 JDBC batches executed ... # 100,000 / 50

With IDENTITY, the same logs show Batch:False for every insert, which makes the diagnosis obvious in minutes. A test that asserts the number of batches, or the number of statements, for an import keeps the problem from returning when someone changes the id strategy.

6When to Leave the ORM

For a one-off load of millions of rows, or a recurring import of large files, the ORM's entity management is overhead we do not need: no dirty checking, cascades or lifecycle callbacks are required to insert rows. JdbcTemplate.batchUpdate with reWriteBatchedInserts=true in the pgjdbc URL is typically several times faster than JPA batching, and PostgreSQL's COPY through CopyManager is faster again. Keeping JPA for the domain logic and using JDBC or COPY for bulk paths is a common and healthy split.

7Follow-up questions

Why is allocationSize 50 a good default?

It cuts sequence calls fiftyfold, matches a typical batch size, and the cost is only gaps in ids when an application restarts with unused reserved values. Larger values reduce calls further but create bigger gaps; gaps in surrogate keys are harmless.

Does saveAll itself batch anything?

No. Spring Data's saveAll simply calls save for each entity, which calls persist for new entities or merge for existing ones. Batching is done entirely by Hibernate at flush time, which is why the id strategy and flush behaviour decide everything.

Is GenerationType.AUTO safe?

With Hibernate 6 and later, AUTO usually maps to a sequence on databases that support them, but the details depend on the dialect and version, so check your version. Stating SEQUENCE explicitly with a named generator is clearer and avoids surprises.

8Conclusion

In this answer, we saw that IDENTITY forces Hibernate to run each INSERT immediately to learn the generated id, so JDBC insert batching is disabled regardless of hibernate.jdbc.batch_size. Switching to a SEQUENCE generator with a matching allocationSize lets ids be assigned before flush, order_inserts keeps batches full, and flushing and clearing every batch keeps memory and dirty checking flat. We verify the result with datasource-proxy or Hibernate statistics, and use JDBC batching or COPY for truly large loads.

What to say in the interviewAbout 80 seconds aloud

Open with

The setting is ignored because of IDENTITY. With IDENTITY the database generates the id when the row is inserted, and Hibernate needs the id immediately to register the entity in the persistence context, so it executes each INSERT on the spot and reads the key back.

Then, if they want more

An insert that has already run cannot go into a later JDBC batch, so batching is silently disabled and we get 100,000 separate round trips.

I would switch the id to a SEQUENCE generator with a SequenceGenerator and allocationSize of 50, with the database sequence incrementing by 50, so Hibernate reserves fifty ids with one nextval call and can delay the inserts until flush. I would set hibernate.order_inserts to true so inserts of different entity types do not break the batches.

Then I would fix the memory side: saveAll of 100,000 entities in one transaction keeps them all managed, and dirty checking gets slower and slower, so I persist in chunks and call flush and clear every 50.

I would verify it rather than trust the configuration, with datasource-proxy showing Batch true and BatchSize 50, or Hibernate statistics counting about 2,000 batches. And if this is a large recurring load, I would use JdbcTemplate batchUpdate with reWriteBatchedInserts, or COPY, instead of the ORM.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Data JPA saveAll of 100,000 entities is slow although...": https://scrivio-interview-library.netlify.app/databases/query-optimization/dfc8309937/