Video in progress
You need to read and process millions of rows from the database using a Spring Data method that returns a Stream. How do you do it without filling memory and without errors?
A Stream<T> from a repository needs an open transaction and a DB cursor, and if the fetch size isn't set correctly the driver still loads everything into memory. On top of that, the persistence context holds every entity. You need fetch size, read-only, detach/clear, and try-with-resources, all of them.
📖 Answer
The basic shape:
@QueryHints({
@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "1000"),
@QueryHint(name = HibernateHints.HINT_READ_ONLY, value = "true")
})
@Query("select o from Order o where o.createdAt < :before")
Stream<Order> streamOld(@Param("before") Instant before);
@Transactional(readOnly = true)
public void export(Instant before, Writer out) {
try (Stream<Order> orders = repo.streamOld(before)) {
orders.forEach(o -> {
writeCsv(out, o);
entityManager.detach(o); // so it doesn't pile up in the persistence context
});
}
}
What can go wrong:
- Without a transaction: Spring Data throws
InvalidDataAccessApiUsageException, because the connection has to stay open. - PostgreSQL: fetch size works only when autocommit is off; otherwise the driver loads the entire result at once. MySQL needs different settings for streaming.
- Persistence context: every loaded entity stays in the first-level cache. If you don't
detachorclear()after every N, the heap fills up anyway. - Lazy associations:
o.getCustomer().getName()inside the loop causes N+1 queries. Take the fields you need with a projection (a DTO or an interface). - A long transaction: a transaction held open for an hour affects replication, vacuum and the connection pool.
In most cases I choose keyset pagination instead of a stream: where id > :lastId order by id limit 1000 in batches, each in its own short transaction. If something fails, it's easy to continue from the last id. A stream is one big operation that can't be restarted.
Sign up to mark studied questions and save your progress.