Video in progress
In Spring Data, after a bulk UPDATE with `@Modifying`, why do you still see the old values?
@Modifying
@Query("update Product p set p.price = p.price * 1.1 where p.category = :c")
int raisePrices(@Param("c") String category);
@Transactional
public BigDecimal raiseAndRead(Long id) {
Product p = repo.findById(id).orElseThrow(); // price = 100
repo.raisePrices(p.getCategory());
return repo.findById(id).orElseThrow().getPrice(); // ?
}
A bulk JPQL/SQL statement goes straight to the database and bypasses the persistence context. Entities that are already loaded stay in their old state. You need to clear the context with clearAutomatically = true or em.clear().
📖 Answer
The answer is 100, not 110. The second findById doesn't go to the database: the entity has been in the persistence context since the first call, and Hibernate returns it from there. The bulk update changed the row in the database, but not the object in memory.
An even worse case: if you changed p before the bulk update and a flush happens afterward, an UPDATE with the old values can go out and overwrite the bulk result.
The fix:
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("update Product p set p.price = p.price * 1.1 where p.category = :c")
int raisePrices(@Param("c") String category);
flushAutomaticallywrites the pending changes before the bulk statement;clearAutomaticallyclears the persistence context afterward, so the next read comes from the database.
clear() makes all managed entities detached. If you change the earlier objects after that, they won't be saved anymore, so keep that in mind too.
One more thing: a bulk operation doesn't increment @Version by itself, and it invalidates second-level cache entries for the whole region. If needed, write set p.version = p.version + 1 by hand.
Sign up to mark studied questions and save your progress.