Read-only transactions
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A product list endpoint loads hundreds of rows and never changes them, yet Hibernate keeps a copy of every row to watch for changes. Telling Spring that the method only reads saves that work.
What readOnly = true changes
A read-only transaction is a real transaction with a begin and an end that promises not to write. Mark it with @Transactional(readOnly = true).
PriceReportService runs in a read-only transaction and wrongly changes a Product. Watch the log for an UPDATE.
Example 1 · PriceReportService.java: a change inside a read-only transaction is dropped
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/readonly/PriceReportService.javapackage com.shoplite.lab.readonly;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.hibernate.Session;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionSynchronizationManager;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
import jakarta.persistence.EntityManager;
@Servicepublic class PriceReportService {
private static final BigDecimal DIWALI_FACTOR = new BigDecimal("0.90");
private final ProductRepository products; private final EntityManager entityManager;
public PriceReportService(ProductRepository products, EntityManager entityManager) { this.products = products; this.entityManager = entityManager; }
@Transactional(readOnly = true) public String diwaliPrice(int productId) { Session session = entityManager.unwrap(Session.class); System.out.println("readOnly: " + TransactionSynchronizationManager.isCurrentTransactionReadOnly() + ", flush mode: " + session.getHibernateFlushMode() + ", entities read-only: " + session.isDefaultReadOnly());
Product product = products.findById(productId).orElseThrow(); // Bug: the report changes the managed entity just to print a sale price product.setPrice(product.getPrice().multiply(DIWALI_FACTOR).setScale(2, RoundingMode.HALF_UP)); return "Diwali price of " + product.getName() + ": " + product.getPrice(); }}
// src/main/java/com/shoplite/lab/readonly/ReadOnlyDemo.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("read-only")public class ReadOnlyDemo implements LabDemo {
private final PriceReportService reports; private final LabDb db;
public ReadOnlyDemo(PriceReportService reports, LabDb db) { this.reports = reports; this.db = db; }
@Override public void run() { System.out.println(reports.diwaliPrice(6)); System.out.println("Price in MySQL after the report: " + db.price(6)); }}DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.readonly.PriceReportService.diwaliPrice]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1554622120<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@5233b7ad] readOnly: true, flush mode: MANUAL, entities read-only: true DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1554622120<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1554622120<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Diwali price of boAt Airdopes 141: 1169.10 Price in MySQL after the report: 1299.00
What this code does
- The transaction is read-only, Hibernate's flush mode is MANUAL and loaded entities are read-only. The report wrongly changed the managed
Product, yet no UPDATE appears in the log. - The returned text shows the in-memory price 1169.10, but MySQL still holds 1299.00. In a read-write transaction this bug would have saved the sale price for everyone.
Three things change:
- Hibernate sets the flush mode to MANUAL and loads entities as read-only, so it keeps no snapshot copies for dirty checking and never flushes. Changes you make to entities are ignored.
- Spring calls
setReadOnly(true)on the JDBC connection. MySQL Connector/J then rejects any data-changing statement on it, and MySQL itself can skip some bookkeeping. - The log shows
,readOnlyat the end of the "Creating new transaction" line.
Fewer snapshots means less memory and less work at the end of every read, which adds up on list endpoints that load hundreds of rows.
Class-level readOnly, method-level writes
ShopLite puts @Transactional(readOnly = true) on the service class and a plain @Transactional on each method that writes. The example adds one write method correctly and forgets the annotation on another.
Example 2 · CatalogService.java: readOnly class default with a write override
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/readonly/CatalogService.javapackage com.shoplite.lab.readonly;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionSynchronizationManager;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Reads are the default here; each write method says so with its own @Transactional. */@Service@Transactional(readOnly = true)public class CatalogService {
private final ProductRepository products;
public CatalogService(ProductRepository products) { this.products = products; }
public BigDecimal price(int productId) { System.out.println("price(): readOnly = " + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); return products.findById(productId).orElseThrow().getPrice(); }
@Transactional public void changePrice(int productId, BigDecimal newPrice) { System.out.println("changePrice(): readOnly = " + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); Product product = products.findById(productId).orElseThrow(); product.setPrice(newPrice); }
/** Wrong: a write method left with the class default. */ public void changePriceForgotAnnotation(int productId, BigDecimal newPrice) { System.out.println("changePriceForgotAnnotation(): readOnly = " + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); Product product = products.findById(productId).orElseThrow(); product.setPrice(newPrice); }}
// src/main/java/com/shoplite/lab/readonly/CatalogDemo.javapackage com.shoplite.lab.readonly;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("catalog")public class CatalogDemo implements LabDemo {
private final CatalogService catalog; private final LabDb db;
public CatalogDemo(CatalogService catalog, LabDb db) { this.catalog = catalog; this.db = db; }
@Override public void run() { System.out.println("Price: " + catalog.price(6)); catalog.changePrice(6, new BigDecimal("1199.00")); System.out.println("After changePrice: " + db.price(6)); catalog.changePriceForgotAnnotation(6, new BigDecimal("999.00")); System.out.println("After changePriceForgotAnnotation: " + db.price(6)); }}price(): readOnly = true DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? Price: 1299.00 changePrice(): readOnly = false DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? After changePrice: 1199.00 changePriceForgotAnnotation(): readOnly = true DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? After changePriceForgotAnnotation: 1199.00
What this code does
price()runs read-only (the class default);changePrice()has its own@Transactional, runs read-write and its UPDATE is sent.changePriceForgotAnnotation()inheritsreadOnly = true: no UPDATE, no error, and the price stays 1199.00 instead of becoming 999.00.
The method-level annotation replaces the class one completely, so changePrice gets a normal read-write transaction.
The trap is a new write method added later without its own annotation: it inherits readOnly = true, Hibernate never flushes, and the change disappears without any error. Code review should check that every method that changes data carries @Transactional.
Find the bug
Find the silent write
The price never changes and there is no error. Tap the line to fix.
The class is annotated with @Transactional(readOnly = true).
Round 1 of 2What readOnly does not promise
readOnly is a hint and an optimisation, not a security check. The two examples show a real UPDATE failing in a read-only transaction, and a readOnly method joining a write transaction.
Example 3 · StockCorrectionService.java: an UPDATE in a read-only transaction
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/readonly/StockCorrectionService.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
@Servicepublic class StockCorrectionService {
private final EntityManager entityManager;
public StockCorrectionService(EntityManager entityManager) { this.entityManager = entityManager; }
/** Wrong on purpose: an UPDATE inside a read-only transaction. */ @Transactional(readOnly = true) public int zeroStockOfInactiveProducts() { return entityManager.createNativeQuery("UPDATE products SET stock = 0 WHERE is_active = FALSE") .executeUpdate(); }}
// src/main/java/com/shoplite/lab/readonly/ReadOnlyWriteDemo.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDemo;
@Component("read-only-write")public class ReadOnlyWriteDemo implements LabDemo {
private final StockCorrectionService corrections;
public ReadOnlyWriteDemo(StockCorrectionService corrections) { this.corrections = corrections; }
@Override public void run() { try { corrections.zeroStockOfInactiveProducts(); } catch (RuntimeException e) { System.out.println(e.getClass().getName()); Throwable root = e; while (root.getCause() != null) { root = root.getCause(); } System.out.println("Root cause: " + root.getClass().getName() + ": " + root.getMessage()); } }}DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.readonly.StockCorrectionService.zeroStockOfInactiveProducts]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(209634457<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@6dc010a2] WARN org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 0, SQLState: S1009 WARN org.hibernate.orm.jdbc.error : Connection is read-only. Queries leading to data modification are not allowed DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback DEBUG o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(209634457<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction org.hibernate.exception.GenericJDBCException Root cause: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
What this code does
- A native UPDATE runs on the read-only connection, and MySQL Connector/J refuses it with SQLState S1009: "Connection is read-only. Queries leading to data modification are not allowed".
- Hibernate wraps it in
GenericJDBCException, and the exception rolls the transaction back.
Example 4 · PriceImportService.java: readOnly is ignored when joining a write transaction
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/readonly/PriceImportService.javapackage com.shoplite.lab.readonly;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
/** A read-write transaction that calls a read-only one. */@Servicepublic class PriceImportService {
private final PriceReportService reports;
public PriceImportService(PriceReportService reports) { this.reports = reports; }
@Transactional public String importAndReport(int productId) { return reports.diwaliPrice(productId); // joins THIS read-write transaction }}
// src/main/java/com/shoplite/lab/readonly/ReadOnlyJoinDemo.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("read-only-join")public class ReadOnlyJoinDemo implements LabDemo {
private final PriceImportService imports; private final LabDb db;
public ReadOnlyJoinDemo(PriceImportService imports, LabDb db) { this.imports = imports; this.db = db; }
@Override public void run() { System.out.println(imports.importAndReport(6)); System.out.println("Price in MySQL after the report: " + db.price(6)); }}DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.readonly.PriceImportService.importAndReport]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(626542001<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@67c64b9c] DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(626542001<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction readOnly: false, flush mode: AUTO, entities read-only: false DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(626542001<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(626542001<open>)] DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Diwali price of boAt Airdopes 141: 1169.10 Price in MySQL after the report: 1169.10
What this code does
- This time
diwaliPrice()(stillreadOnly = true) is called from a read-write transaction. It participates, and its probe printsreadOnly: false, flush mode: AUTO. - The accidental change is flushed at commit: MySQL now holds the sale price 1169.10.
readOnlyprotected nothing here.
readOnly applies only when the method starts a transaction. If a read-write transaction is already running and calls a readOnly method, the method just joins it, and its changes are saved like any others.
An explicit UPDATE inside a real read-only transaction does fail: the driver answers "Connection is read-only. Queries leading to data modification are not allowed". That is a side effect of the JDBC flag, not an access-control rule. Who may change what is decided by roles and owner checks (the Security section) and by the database user's grants, never by readOnly.
Predict the output
Is the change saved?
Each method changes a product, then returns normally.
Round 1 of 3
A read-write transaction calls a readOnly method of another bean.
Isolation levels in one view
An isolation level decides what one transaction sees of other transactions' changes while it runs.
StockAuditService reads the same stock twice while another thread commits a restock in between. It runs once under each of two isolation levels.
Example 5 · StockAuditService.java: REPEATABLE READ vs READ COMMITTED
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/readonly/StockAuditService.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Isolation;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.ProductRepository;
/** Reads the same stock twice in one transaction; between the reads, someone else commits a change. */@Servicepublic class StockAuditService {
private final ProductRepository products;
public StockAuditService(ProductRepository products) { this.products = products; }
@Transactional(readOnly = true) public String readTwiceRepeatableRead(int productId, Runnable betweenReads) { return readTwice(productId, betweenReads); }
@Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) public String readTwiceReadCommitted(int productId, Runnable betweenReads) { return readTwice(productId, betweenReads); }
private String readTwice(int productId, Runnable betweenReads) { int first = products.findStockById(productId); betweenReads.run(); int second = products.findStockById(productId); return "first read " + first + ", second read " + second; }}
// src/main/java/com/shoplite/lab/readonly/IsolationDemo.javapackage com.shoplite.lab.readonly;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.lab.basics.RestockService;
@Component("isolation")public class IsolationDemo implements LabDemo {
private final StockAuditService audit; private final RestockService restock; private final LabDb db;
public IsolationDemo(StockAuditService audit, RestockService restock, LabDb db) { this.audit = audit; this.restock = restock; this.db = db; }
@Override public void run() { System.out.println("REPEATABLE READ: " + audit.readTwiceRepeatableRead(9, this::restockOnAnotherThread)); System.out.println("READ COMMITTED: " + audit.readTwiceReadCommitted(9, this::restockOnAnotherThread)); System.out.println("Stock in MySQL now: " + db.stock(9)); }
/** Another "request": a new thread, so a separate transaction that commits before we read again. */ private void restockOnAnotherThread() { Thread other = new Thread(() -> restock.restock(9, 10)); other.start(); try { other.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}
interface ProductRepository extends JpaRepository<Product, Integer> { @Query("select p.stock from Product p where p.id = :id") int findStockById(@Param("id") Integer id);}REPEATABLE READ: first read 30, second read 30 READ COMMITTED: first read 40, second read 50 Stock in MySQL now: 50
What this code does
- Between the two reads another thread restocks 10 units and commits. Under MySQL's default REPEATABLE READ the second read still sees the first snapshot: 30 and 30.
- Under READ COMMITTED the second read sees the new commit: 40, then 50. The stock was 40 by then because the first run had already added 10.
findStockByIdreads only the number, so Hibernate cannot answer from its first-level cache; the difference really comes from MySQL.
From weakest to strongest, the levels are READ UNCOMMITTED (can see uncommitted changes), READ COMMITTED (each statement sees the latest committed data), REPEATABLE READ (the transaction keeps the snapshot from its first read) and SERIALIZABLE (as if transactions ran one after another). MySQL's InnoDB uses REPEATABLE READ by default, and ISOLATION_DEFAULT in the log means "use the database default". Change it per method only with a reason, such as @Transactional(isolation = Isolation.READ_COMMITTED) for a long report that should see fresh numbers.
What the example shows:
- REPEATABLE READ: two reads of the same row in one transaction give the same answer (Example 5: 30 and 30).
- READ COMMITTED: the second read sees another transaction's commit (40, then 50).
- Neither level stops two transactions from overwriting each other's updates; that is the locking lesson.
Routing read-only transactions to a replica
A replica is a copy of the database that follows the main (primary) server and serves reads. It can lag a little behind the primary.
The snippet chooses the target data source from the transaction's read-only flag.
class ReadWriteRoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return TransactionSynchronizationManager.isCurrentTransactionReadOnly() ? "replica" : "primary"; }}// Wrap it in LazyConnectionDataSourceProxy, so the connection is taken only// after the transaction (and its readOnly flag) has started.Large apps send read-only transactions to replicas so the primary only handles writes. Spring's AbstractRoutingDataSource can choose the target for each connection, and the read-only flag of the transaction is the natural key.
Replica routing is an idea to know for interviews, not something ShopLite needs. Replicas lag a little, so a read right after a save may not see it yet.
Next step
Check your understanding
12 quick questions