Video in progress
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:
- Hibernate switches the session to
FlushMode.MANUALand doesn't keep snapshots of loaded entities. Where you read lots of objects, the memory savings are noticeable. - JDBC —
connection.setReadOnly(true). The PostgreSQL driver opens the transaction asREAD ONLY, MySQL applies some optimizations. - Routing —
AbstractRoutingDataSourceor 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.
Sign up to mark studied questions and save your progress.