Video in progress
If you need to process a million rows through Hibernate, how do you avoid `OutOfMemoryError`?
Don't fetch everything with a single getResultList(): read in pieces with ScrollableResults or a stream, call flush()/clear() after every N rows, or use a StatelessSession, which has no persistence context. Even better, split the work into separate transactions by ID ranges.
📖 Answer
The root of the problem is that the persistence context holds all the loaded entities and their snapshots. findAll() plus a loop means a million objects × 2 in memory.
Option 1: stream and clear:
@Transactional
public void recalc() {
try (Stream<Invoice> s = em.createQuery("select i from Invoice i", Invoice.class)
.setHint("org.hibernate.fetchSize", 500)
.getResultStream()) {
AtomicInteger n = new AtomicInteger();
s.forEach(inv -> {
inv.recalculateTax();
if (n.incrementAndGet() % 500 == 0) {
em.flush();
em.clear();
}
});
}
}
On PostgreSQL the fetch size works only when auto-commit is off (that is, inside a transaction); otherwise the driver pulls everything into memory anyway. On MySQL you need a separate setting for streaming.
Option 2: StatelessSession: no cache, no dirty checking, no cascade, and you call update() yourself. Suitable for ETL.
Option 3: chunks by keyset:
select * from invoice where id > :lastId order by id limit 1000
Each chunk is a separate short transaction. If something fails, only one chunk is rolled back instead of everything, and you can resume from lastId. A long transaction also blocks vacuum on PostgreSQL, so this is the option I pick most often.
And the last question: do you have to do this in Java at all? A lot of calculations finish in seconds with a single update ... set ... from ... SQL statement.
Sign up to mark studied questions and save your progress.