Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a service method that imports 500,000 records with JPA efficiently, and explain each choice.

We give the entity SEQUENCE ids with an allocationSize that matches hibernate.jdbc.batch_size, persist records in a loop, and every batch_size entities call flush() and clear() so the batch is sent and the persistence context is emptied. We commit in chunks, for example one TransactionTemplate transaction per 5,000 records, so a failure does not undo everything and locks stay short, and we bypass the second-level cache for the import. If the load has no domain logic at all, JdbcTemplate.batchUpdate or the database's COPY is faster still.

Why this question is asked

Importing half a million rows is where the default way of using JPA stops working. A naive loop with repository.save() inside one transaction can take tens of minutes, run out of heap, or hold locks for so long that other users are blocked. Interviewers ask for code because each line of a good import exists for a reason, and they want to hear those reasons. In this answer, we will look at the naive version and why it fails, then build the efficient method step by step: id generation and batching, flush and clear, chunked transactions, cache settings, and finally when to skip JPA entirely.

1The Naive Import and Why It Fails

Let us start with the version most people write first. It reads records and saves each one in a single transaction.

Java
@Transactional
public void importAll(List<Record> records) { // 500,000 records
for (Record r : records) {
customerRepository.save(Customer.from(r)); // IDENTITY id: one insert round trip each
}
} // one commit at the very end

Three things go wrong. First, every entity stays in the persistence context, Hibernate's map of managed entities, until the transaction ends, each with a snapshot copy used for dirty checking. Half a million entities and their snapshots can easily use more than a gigabyte of heap, and every flush has to scan all of them. Second, with IDENTITY ids each save runs its insert immediately, so there is no batching and we pay 500,000 round trips. Third, it is one transaction: a bad record at row 499,000 rolls back everything, and the transaction holds its locks and its undo data for the whole run.

2Ids and Batch Size That Work Together

JDBC batching sends many executions of one insert statement in one round trip. Hibernate only does that for inserts if it can assign the id before running the insert, which IDENTITY prevents. So we switch to a sequence and let Hibernate reserve ids in blocks with the pooled optimizer.

Java
@Entity
class Customer {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_seq")
@SequenceGenerator(name = "customer_seq", sequenceName = "customer_seq", allocationSize = 50)
Long id;
}
-- the sequence must match: CREATE SEQUENCE customer_seq INCREMENT BY 50;
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true

Notice that allocationSize and batch_size are both 50. That is not required, but it means each batch needs exactly one sequence call, which keeps the arithmetic simple: 500,000 rows means 10,000 batches and 10,000 sequence calls instead of a million round trips.

3Flush and Clear Every Batch

Batching alone does not fix the memory problem, because entities still pile up in the persistence context. So every 50 entities we call flush(), which sends the pending inserts as one batch, and clear(), which detaches everything so the garbage collector can reclaim it. The persistence context then never holds more than 50 entities.

Java
for (int i = 0; i < chunk.size(); i++) {
em.persist(Customer.from(chunk.get(i)));
if ((i + 1) % BATCH == 0) { // BATCH = 50
em.flush(); // one JDBC batch of 50 inserts
em.clear(); // persistence context back to 0 entities
}
}
em.flush(); // the remainder
em.clear();

We call em.persist() rather than repository.save(). The reason is that save() first checks whether the entity is new; if the entity had an assigned id, save() would call merge(), which runs a select per row. persist() states our intent directly.

4Commit in Chunks

Next we split the import into chunks of, say, 5,000 records, each in its own transaction. TransactionTemplate lets us do that inside one method without self-invocation problems. If chunk 73 fails, chunks 1 to 72 stay committed, we log which chunk failed, and we can resume from it. Each transaction is short, so row locks and undo data are released every few seconds and other users are not blocked.

Java
@Service
class CustomerImporter {
private static final int BATCH = 50, CHUNK = 5_000;
private final EntityManager em;
private final TransactionTemplate tx;
CustomerImporter(EntityManager em, PlatformTransactionManager tm) {
this.em = em;
this.tx = new TransactionTemplate(tm);
}
public ImportResult importAll(Stream<Record> source) {
AtomicInteger saved = new AtomicInteger();
Iterators.chunks(source, CHUNK).forEach(chunk -> // any helper that groups 5,000 records
tx.executeWithoutResult(status -> {
Session session = em.unwrap(Session.class);
session.setCacheMode(CacheMode.IGNORE); // no second-level cache writes
for (int i = 0; i < chunk.size(); i++) {
em.persist(Customer.from(chunk.get(i)));
if ((i + 1) % BATCH == 0) { em.flush(); em.clear(); }
}
em.flush(); em.clear();
saved.addAndGet(chunk.size()); // 5,000 per committed chunk
}));
return new ImportResult(saved.get()); // 500,000
}
}
Step throughOne chunk of the import
  1. Begin transactionTransactionTemplate, one per 5,000 records
  2. persist() 50 entitiesids from the sequence, no SQL yet
  3. flush() and clear()one batch of 50 inserts, context emptied
  4. More records in this chunk?
    Yespersist the next 50Nocommit the chunk
  5. Next chunka failure only rolls back these 5,000

5 steps in order. Play them, or step through them one at a time.

Notice that we read the source as a Stream. Loading all 500,000 records into a list first would put the memory problem back in a different place. The chunking helper is not part of the JDK; Java 24 and later can use the Gatherers.windowFixed(5_000) gatherer for it.

5Keep Caches Out of the Way

If the entity is cached in the second-level cache, a shared cache across sessions, every insert would also write an entry into it. For an import, that is wasted work and it pushes useful entries out of the cache. Setting the session's cache mode to IGNORE, as in the code above, stops those writes; the standard JPA alternative is the jakarta.persistence.cache.storeMode property set to CacheStoreMode.BYPASS. If the entity is not cached at all, this step is not needed.

6When to Skip JPA Entirely

Everything above keeps the entity model, which is right when each record goes through domain logic: validation in the entity, derived fields, cascades to children. If the import is a pure load, the rows map straight to columns with no behaviour, JPA adds overhead we do not need: entity objects, persistence context bookkeeping and dirty checking. JdbcTemplate's batchUpdate sends the same batched inserts with much less work per row, and PostgreSQL's COPY streams rows in a single command and is usually the fastest option of all.

Java
jdbcTemplate.batchUpdate(
"insert into customer (id, name, email) values (nextval('customer_seq'), ?, ?)",
records, 1_000,
(ps, r) -> { ps.setString(1, r.name()); ps.setString(2, r.email()); });

As a rough guide on the same hardware, the naive loop may take over half an hour for 500,000 rows, the batched JPA version a few minutes, JdbcTemplate batches about a minute and COPY seconds. The exact numbers depend on row size, indexes and the network, so we measure on our own data before choosing.

7Follow-up questions

Why not use Hibernate's StatelessSession?

It is a good option for imports. A StatelessSession has no persistence context, no dirty checking and no cascades, so there is nothing to clear, and it supports batching too. The cost is that it skips features such as cascades, the second-level cache and lifecycle callbacks, so it fits records without much domain behaviour.

How do you make the import restartable?

Record the last committed chunk number, or an input offset, in a table inside the same transaction as the chunk. On restart, skip to the next chunk. Spring Batch provides this pattern out of the box with chunk-oriented steps and a job repository.

Should secondary indexes stay during the import?

For a one-off load into an empty table, creating indexes after the load is usually faster, because building an index once is cheaper than updating it 500,000 times. For a table that is in use, we keep the indexes and accept the cost.

8Conclusion

In this answer, we built a 500,000-record import with JPA. SEQUENCE ids with a pooled optimizer let Hibernate batch inserts, batch_size and order_inserts group them, flush() and clear() every 50 entities keep memory flat, and one TransactionTemplate transaction per 5,000 records keeps locks short and failures contained. We bypassed the second-level cache for the import and saw that a pure load without domain logic is better served by JdbcTemplate batches or COPY.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write the import around four choices. First, ids: I would use a SEQUENCE generator with allocationSize matching the sequence's increment, say 50, because IDENTITY forces Hibernate to insert each row immediately and disables insert batching.

Then, if they want more

Then I set hibernate.jdbc.batch_size to 50 and order_inserts to true. Second, memory: I persist in a loop and every 50 entities call flush and clear on the EntityManager. Flush sends one JDBC batch, clear detaches the entities so the persistence context never grows beyond 50 and dirty checking stays cheap.

I use persist rather than save, to avoid merge and its select for entities with assigned ids. Third, transactions: I commit in chunks of a few thousand records with a TransactionTemplate per chunk, so a bad record rolls back only its chunk, locks are released quickly, and I can record progress to resume.

I read the input as a stream so I never hold all half a million records. Fourth, I set the session cache mode to IGNORE so the import does not fill the second-level cache. And if the data has no domain logic, I would skip JPA and use JdbcTemplate batchUpdate, or PostgreSQL COPY, which is much faster.

About this answer

Last updated
12 November 2026
Versions it names
Java 24
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 "Write a service method that imports 500,000 records with JPA efficiently, and explain...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/55af7360c3/