Video in progress
You need to export a table with a million rows to CSV. What do you do in Spring Data JPA instead of findAll()?
findAll() loads every row into the heap at once. You need Stream<T> or keyset-based batch reads, a fetch size, a readOnly transaction and detaching/clearing entities; a DTO projection or JdbcClient is often the most economical.
📖 Answer
The problem is in two places: the JDBC driver pulls the whole result, and the persistence context holds every entity (with a snapshot).
Option 1 — reading with a Stream:
@QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "1000"))
@Query("select new com.shop.OrderRow(o.id, o.total, o.createdAt) from Order o")
Stream<OrderRow> streamAllRows();
@Transactional(readOnly = true)
public void export(Writer out) {
try (Stream<OrderRow> rows = repo.streamAllRows()) {
rows.forEach(r -> csv.write(out, r));
}
}
- A
Streamworks only inside an open transaction and must be closed withtry-with-resources, otherwise the connection hangs. - The PostgreSQL driver respects
fetchSizeonly whenautocommit=false, which is exactly what you have inside a transaction. MySQL needs different settings for streaming. - Read a DTO projection, not entities: then there is no snapshot and no dirty checking.
Option 2 — keyset batches:
List<OrderRow> page;
long lastId = 0;
do {
page = repo.findNextPage(lastId, PageRequest.ofSize(5000)); // where id > :lastId order by id
page.forEach(r -> csv.write(out, r));
if (!page.isEmpty()) lastId = page.get(page.size() - 1).id();
} while (!page.isEmpty());
There is no long transaction here, and the connection goes back after each batch. Don't use OFFSET: it gets very slow on the last pages.
Option 3 — bypass JPA. An export is a plain read; JdbcClient or JdbcTemplate + RowCallbackHandler uses the least memory and runs fastest.
Either way, don't hold the export inside an HTTP request for 10 minutes: run it as a background job, write the file to storage and hand out a link when it's ready.
Sign up to mark studied questions and save your progress.