Dirty checking: updates without save()
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop admin changes a product price. With plain JDBC every change needed its own UPDATE statement, and forgetting to run it lost the change silently. Hibernate can find the changes and write them for you.
Change a managed entity, get an UPDATE at commit
Dirty checking is Hibernate's step at flush that finds changed managed entities: it compares each one with the copy taken when it was loaded and sends an UPDATE for every entity that differs.
The listing loads product 6, changes its price with a setter and ends the method. There is no save() call anywhere.
Example 1 · A price change without save()
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/DirtyCheckingDemo.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("dirty-checking")public class DirtyCheckingDemo implements LabDemo {
private final ProductRepository products;
public DirtyCheckingDemo(ProductRepository products) { this.products = products; }
@Override @Transactional public void run() { Product airdopes = products.findById(6).orElseThrow(); System.out.println("loaded: " + airdopes);
airdopes.setPrice(new BigDecimal("1199.00")); System.out.println("changed in memory: " + airdopes); System.out.println("no save() call; the method ends here"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=dirty-checking --logging.level.org.hibernate.orm.jdbc.bind=TRACE" 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=? TRACE org.hibernate.orm.jdbc.bind : binding parameter (1:INTEGER) <- [6] loaded: Product[id=6, sku=ACC-AD141, price=1299.00, stock=120] changed in memory: Product[id=6, sku=ACC-AD141, price=1199.00, stock=120] no save() call; the method ends here DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? TRACE org.hibernate.orm.jdbc.bind : binding parameter (1:BOOLEAN) <- [true] TRACE org.hibernate.orm.jdbc.bind : binding parameter (2:INTEGER) <- [4] TRACE org.hibernate.orm.jdbc.bind : binding parameter (3:VARCHAR) <- [boAt Airdopes 141] TRACE org.hibernate.orm.jdbc.bind : binding parameter (4:NUMERIC) <- [1199.00] TRACE org.hibernate.orm.jdbc.bind : binding parameter (5:VARCHAR) <- [ACC-AD141] TRACE org.hibernate.orm.jdbc.bind : binding parameter (6:INTEGER) <- [120] TRACE org.hibernate.orm.jdbc.bind : binding parameter (7:INTEGER) <- [6]
What this code does
- The SELECT loads product 6 and makes it managed.
setPriceonly changes the Java object: no SQL appears between "loaded" and "no save() call". - When
run()returns, Spring commits; Hibernate flushes, finds the price differs from the snapshot and sends the UPDATE. The bind lines (turned on withorg.hibernate.orm.jdbc.bind=TRACE) show parameter 4 is the new price 1199.00. - The UPDATE lists all six columns, not only
price. That is Hibernate's default; the unchanged values are simply written back as they were.
An entity is dirty when one of its fields now differs from what was loaded. Dirty checking runs at every flush, and Spring flushes when a @Transactional method commits.
The rule has two parts: the object must be managed (loaded in this transaction) and the transaction must commit. The rest of this lesson is about what happens when one part is missing.
How it works: the snapshot
A snapshot is Hibernate's private copy of every column value loaded for an entity. At flush, Hibernate compares the entity with its snapshot and sends an UPDATE only when they differ.
Three products are touched: one set to its current value, one changed and changed back, one really changed. Which of them get an UPDATE?
Example 2 · The snapshot compares values, not setter calls
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/SnapshotDemo.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("snapshot")public class SnapshotDemo implements LabDemo {
private final ProductRepository products;
public SnapshotDemo(ProductRepository products) { this.products = products; }
@Override @Transactional public void run() { Product cleanCode = products.findById(9).orElseThrow(); cleanCode.setPrice(new BigDecimal("499.00")); // the same value it already has System.out.println("product 9: set price to the same value");
Product pragmatic = products.findById(10).orElseThrow(); pragmatic.setStock(21); // 22 -> 21 pragmatic.setStock(22); System.out.println("product 10: changed stock and changed it back");
Product atomic = products.findById(11).orElseThrow(); atomic.setStock(atomic.getStock() - 3); System.out.println("product 11: stock 50 -> 47"); System.out.println("-- method ends, Spring commits"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=snapshot --logging.level.org.hibernate.orm.jdbc.bind=TRACE" 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=? product 9: set price to the same value 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=? product 10: changed stock and changed it back 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=? product 11: stock 50 -> 47 -- method ends, Spring commits DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? TRACE org.hibernate.orm.jdbc.bind : binding parameter (1:BOOLEAN) <- [true] TRACE org.hibernate.orm.jdbc.bind : binding parameter (2:INTEGER) <- [5] TRACE org.hibernate.orm.jdbc.bind : binding parameter (3:VARCHAR) <- [Atomic Habits] TRACE org.hibernate.orm.jdbc.bind : binding parameter (4:NUMERIC) <- [399.00] TRACE org.hibernate.orm.jdbc.bind : binding parameter (5:VARCHAR) <- [BK-ATOMIC] TRACE org.hibernate.orm.jdbc.bind : binding parameter (6:INTEGER) <- [47] TRACE org.hibernate.orm.jdbc.bind : binding parameter (7:INTEGER) <- [11]
What this code does
- Three products were loaded and setters were called on all three, yet only one UPDATE was sent. Its last bind value,
(7:INTEGER) <- [11], shows it is for product 11 (the SELECT bind lines are left out here). - Product 9 got the same price it already had, and product 10 went 22 to 21 and back to 22. At flush both equal their snapshots, so they are not dirty.
- Only product 11 ends with a value (47) that differs from its snapshot (50).
Hibernate does not watch your setter calls; it compares values. By default the UPDATE lists every updatable column, as the first listing showed, so Hibernate can prepare one UPDATE text per entity type and reuse it. Hibernate's @DynamicUpdate annotation on an entity writes only the changed columns, at the cost of building the SQL each time.
The snapshot costs memory and the comparison costs time for every managed entity at every flush. Loading 10,000 products just to show them doubles the memory and compares 10,000 objects for nothing. That is one reason read-only methods should say readOnly = true (last section).
Predict the output
Does commit send an UPDATE?
Each method is @Transactional. Pick what Hibernate sends at commit.
Round 1 of 4
Product 9 costs 499.00 in the database.
Calling save() on a managed entity is redundant
save() on a managed entity changes nothing: Spring Data sees an id, calls merge, and merging a managed object simply returns that same object. The UPDATE still comes from dirty checking at commit.
The listing lowers the stock of a managed product, then calls save() on it and prints whether save() returned the same object.
Example 3 · save() on a managed entity changes nothing
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/SaveRedundantDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("save-redundant")public class SaveRedundantDemo implements LabDemo {
private final ProductRepository products;
public SaveRedundantDemo(ProductRepository products) { this.products = products; }
@Override @Transactional public void run() { Product powerBank = products.findById(7).orElseThrow(); powerBank.setStock(powerBank.getStock() - 1);
Product saved = products.save(powerBank); // not needed: the object is managed System.out.println("save() returned the same object? " + (saved == powerBank)); System.out.println("-- method ends, Spring commits"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=save-redundant" 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=? save() returned the same object? true -- method ends, Spring commits DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
What this code does
save()returned the very same object and sent no SQL of its own. For an object with an id it callsmerge, and merging an object that is already managed returns it unchanged.- The one UPDATE comes at commit from dirty checking, exactly as it would without the
save()line. Delete the line and the log is identical.
The call does no harm, but it misleads readers: it suggests that without save() the change would be lost, and it hides the real rule (managed plus commit). ShopLite services load, change and return; save() is kept for new objects, which must be persisted.
Changes to detached objects are silently lost
A detached entity has an id and a row, but no persistence context tracks it, so changes to it never reach the database. Entities loaded outside a transaction are detached at once.
The listing calls findById in a method without @Transactional, sets the stock to 25 and reads the row back.
Example 4 · A change outside a transaction is lost
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/LostChangesDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("lost-changes")public class LostChangesDemo implements LabDemo {
private final ProductRepository products;
public LostChangesDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // no @Transactional here Product mouse = products.findById(8).orElseThrow(); // its own short transaction mouse.setStock(25); System.out.println("changed in memory: " + mouse);
Product fromDb = products.findById(8).orElseThrow(); System.out.println("read back: " + fromDb); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=lost-changes" 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=? changed in memory: Product[id=8, sku=ACC-M331, price=849.00, stock=25] 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=? read back: Product[id=8, sku=ACC-M331, price=849.00, stock=0]
What this code does
run()has no@Transactional, sofindByIdruns in its own short transaction and returns an object that is already detached.setStock(25)changes only that Java object.- No UPDATE appears anywhere in the log, and reading the row back gives stock 0. The 25 new mice exist only in memory, and nothing warns you.
The change is lost silently: the object is in no persistence context, so no flush ever looks at it. The bug appears when a method without @Transactional loads an entity and calls a setter, when an entity is kept in a field or a cache between requests, or when a @Transactional method is called from inside its own class (the Transactions module explains why that call skips the transaction).
The fix is always the same shape: one @Transactional service method that loads the entity and changes it.
Find the bug
Find the lost update
Each change is never saved and no error appears. Tap the line that causes it.
Stock added to a product is not saved.
Round 1 of 3Accidental updates, and readOnly transactions
readOnly = true, set as @Transactional(readOnly = true), marks a method that only reads: Hibernate loads entities read-only, keeps no snapshot and does not flush, so no UPDATE can be sent.
A "mapper" method calls setPrice to show a price with GST. The listing runs it once in a normal transaction and once with readOnly = true.
Example 5 · A mapper that writes to the database, and readOnly = true
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/PriceDisplayService.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class PriceDisplayService {
private static final BigDecimal GST = new BigDecimal("1.18");
private final ProductRepository products;
public PriceDisplayService(ProductRepository products) { this.products = products; }
@Transactional public String priceWithGst(int id) { return toDisplay(products.findById(id).orElseThrow()); }
@Transactional(readOnly = true) public String priceWithGstReadOnly(int id) { return toDisplay(products.findById(id).orElseThrow()); }
// The bug: a "mapper" that changes the entity instead of computing a new value private String toDisplay(Product product) { product.setPrice(product.getPrice().multiply(GST).setScale(2, RoundingMode.HALF_UP)); return product.getName() + ": Rs " + product.getPrice() + " incl. GST"; }}
// src/main/java/com/shoplite/lab/AccidentalUpdateDemo.java (its run method)@Overridepublic void run() { System.out.println("-- read-write transaction"); System.out.println(display.priceWithGst(9)); System.out.println("price in the database now: " + products.findById(9).orElseThrow().getPrice());
System.out.println("-- readOnly transaction"); System.out.println(display.priceWithGstReadOnly(10)); System.out.println("price in the database now: " + products.findById(10).orElseThrow().getPrice());}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=accidental-update" -- read-write 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 org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? Clean Code: Rs 588.82 incl. GST 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 in the database now: 588.82 -- readOnly 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=? The Pragmatic Programmer: Rs 767.00 incl. GST 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 in the database now: 650.00
What this code does
toDisplaycallssetPriceto show the price with 18% GST. In the read-write transaction dirty checking saves that: Clean Code now costs 588.82 in the database, and every page view would raise it by another 18%.- The same code in a
readOnly = truetransaction sends no UPDATE: Hibernate keeps no snapshot and does not flush, so The Pragmatic Programmer still costs 650.00. - readOnly is the safety net, not the fix. The real fix is a mapper that computes
price.multiply(GST)into a new value and never touches the entity (Practice 4).
Dirty checking also writes changes you did not mean to save. A mapper that calls a setter on a managed entity changes the row at commit, so a read endpoint quietly writes to the database on every call. ShopLite uses two fixes: mappers never call setters (they read fields and build a new DTO), and read-only service methods use @Transactional(readOnly = true).
A method that is meant to write must not be marked readOnly = true: its changes would vanish silently.
readOnly = true Spring also marks the JDBC connection read-only, and the MySQL driver then refuses writes: a hand-written UPDATE inside such a method fails with "Connection is read-only. Queries leading to data modification are not allowed". That is a good thing: a read method should never write.Next step
Check your understanding
12 quick questions