Video in progress

A report endpoint that loads a huge number of entities has increased GC pauses. How do you reduce memory on the Hibernate side?

For every managed entity, Hibernate holds the entity itself, the snapshot, the EntityEntry and the collection wrappers. For a report, a DTO projection instead of entities, a read-only hint, cursor-based reading and, if needed, aggregating at the SQL level cut memory several times over.

📖 Answer

First I look at a heap dump or a JFR allocation profile. If it's a Hibernate problem, StatefulPersistenceContext, EntityEntry, Object[] (the loaded state) and PersistentBag usually sit at the top of the dominator list.

Then step by step:

  1. Hand the aggregation to the database. Many reports do stream().groupingBy() in Java: they load 200 thousand entities to produce a 30-row table. If you do it in SQL with group by, the memory problem disappears entirely.

  2. A DTO projection. Only the columns you need, and nothing lands in the context:

select new com.app.SalesRow(s.region, s.day, sum(s.amount))
from Sale s where s.day between :from and :to
group by s.region, s.day
  1. If you need entities, make them read-only. @Transactional(readOnly = true) or HINT_READ_ONLY turns off the snapshot, which is roughly half the memory.

  2. Stream instead of loading everything. getResultStream() + fetchSize + periodic em.detach()/clear(), and write the result straight to an OutputStream (CSV).

  3. Check for EAGER chains. A single @ManyToOne(EAGER) drags in the whole graph: 5 times as many objects without anyone noticing.

I always measure the result: allocation rate (MB/s) and GC pauses before and after. Sometimes moving the report to a separate replica or an OLAP database is the right architectural decision.