Video in progress
What does @Transactional(readOnly = true) actually change at the Hibernate level?
Spring puts the Hibernate session into read-only mode and sets the flush mode to MANUAL. As a result, no snapshots are kept for loaded entities and there is no dirty checking or flush; the JDBC connection is also marked read-only.
📖 Answer
The practical benefit is memory and CPU. In a report method that reads 10 thousand entities, snapshots mean twice the memory; in read-only mode they aren't there.
@Transactional(readOnly = true)
public List<ProductView> catalog() {
return repo.findAllActive().stream().map(ProductView::from).toList();
}
Surprises:
- if you modify an entity inside a read-only method, there's no error: the change silently isn't saved. That sometimes hides a bug;
- read-only is not a protection mechanism. If you call
em.persist()or write a nativeUPDATE, the database sometimes executes it (it depends on the driver and the database). With the PostgreSQL driver, a read-only connection rejects writes; - routing to a replica doesn't happen on its own. That needs a separate routing datasource, which can choose based on the
readOnlyflag.
If a regular @Transactional method (default REQUIRED) is called from inside a read-only transaction, it joins the outer read-only transaction, and writes may still not get flushed. That's why I put @Transactional(readOnly = true) on the service class and write a separate @Transactional on the methods that write. That works well when each method starts its own transaction.
Sign up to mark studied questions and save your progress.