Video in progress
Which price does the last line of this code print, and why?
@Transactional
public void reprice() {
Product p = em.find(Product.class, 1L); // price = 100
em.createQuery("update Product p set p.price = p.price * 2")
.executeUpdate();
System.out.println(p.getPrice());
}
The old price, 100. A bulk JPQL UPDATE goes straight to the database and does not update the Product object that is already loaded in the persistence context.
📖 Answer
A bulk update/delete doesn't load entities and doesn't go through dirty checking: Hibernate sends a single SQL statement, that's all. The price in the database is now 200, but p in memory still shows 100.
Even worse: if at the end of this method you change another field of p, dirty checking writes all the columns in the UPDATE and overwrites the 200 in the database with 100 again.
How to fix it:
em.createQuery("update Product p set p.price = p.price * 2").executeUpdate();
em.clear(); // or em.refresh(p)
Product fresh = em.find(Product.class, 1L); // 200
In Spring Data:
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("update Product p set p.price = p.price * 2")
int doublePrices();
flushAutomatically sends any not-yet-written changes to the database before the bulk query, and clearAutomatically clears the context afterward.
Bulk operations also don't increment @Version on their own (unless you write update versioned in HQL), and you need to be careful with lifecycle callbacks and the second-level cache too.
Sign up to mark studied questions and save your progress.