Video in progress

What does `@Transactional(readOnly = true)` actually give the database in Spring, and what doesn't it give?

In Hibernate, dirty checking and flush are switched off, which saves memory and CPU; the JDBC connection gets setReadOnly(true) and PostgreSQL makes the transaction read-only. But it doesn't speed up the query by itself and doesn't route to a replica: you have to configure that separately.

📖 Answer

It has an effect at several layers:

  • Hibernate. The session goes to FlushMode.MANUAL, and no dirty-checking snapshot is kept for read-only entities. In a method that loads thousands of entities, this saves a noticeable amount of memory.
  • JDBC/PostgreSQL. PgJDBC turns Connection.setReadOnly(true) into BEGIN READ ONLY. If you run an INSERT/UPDATE inside such a transaction, you get cannot execute UPDATE in a read-only transaction, which protects against accidental writes.
  • Routing. If you set up an AbstractRoutingDataSource yourself, you can pick a replica based on this flag. By itself, Spring sends nothing to a replica.

What it doesn't give you:

@Transactional(readOnly = true)
public List<OrderDto> report() {
    return repo.findAll().stream().map(OrderDto::from).toList(); // can still be N+1
}

The query plan, the indexes, N+1: everything stays unchanged. One more thing: readOnly is only taken into account when a new transaction starts. If it's called from inside a writing method (REQUIRED), the outer transaction's rules apply.

I make it the default on service methods that only read: it's cheap and catches mistakes early.