Video in progress

Middle 🌱 Spring

What does @Transactional(readOnly = true) actually give you?

Hibernate turns off flush and dirty checking (saving memory and CPU), the JDBC connection becomes read-only, and some routing setups use it to send the query to a replica. But it doesn't 100% forbid writes.

📖 Answer

What changes:

  1. Hibernate switches the session to FlushMode.MANUAL and doesn't keep snapshots of loaded entities. Where you read lots of objects, the memory savings are noticeable.
  2. JDBC — connection.setReadOnly(true). The PostgreSQL driver opens the transaction as READ ONLY, MySQL applies some optimizations.
  3. Routing — AbstractRoutingDataSource or proxies can use this flag to send the query to a replica.
@Service
@Transactional(readOnly = true)   // class-level default
public class CatalogService {
    public List<ProductDto> search(String q) { ... }

    @Transactional                // overridden for the writing method
    public void rename(long id, String name) { ... }
}

In interviews people often say "with readOnly you can't write". Actually it depends on the driver and the database — in some setups a native UPDATE still goes through. Think of it as an optimization and a statement of intent, not as protection.