Video in progress
If you modify an entity inside a transaction, why is it written to the database even though you never call save()?
This is dirty checking. An entity loaded inside a transaction becomes managed, and Hibernate remembers its initial copy. On flush or commit it finds the changed fields and sends the UPDATE itself.
📖 Answer
@Transactional
public void rename(Long id, String newName) {
Product p = repo.findById(id).orElseThrow();
p.setName(newName);
// no save(), but the UPDATE goes out at commit
}
What happens inside:
findByIdputs the entity into the persistence context and saves a snapshot of its state.- You call the setter, and the plain Java object changes.
- A flush happens before the commit: Hibernate compares every managed entity with its snapshot and writes an UPDATE for the ones that differ.
It's convenient: the service code is clean, and save() isn't required. But a field you changed "just for display" gets written to the database too:
@Transactional
public ProductDto show(Long id) {
Product p = repo.findById(id).orElseThrow();
p.setPrice(p.getPrice().multiply(rate)); // a calculation for the UI... but it changed in the database too!
return ProductDto.from(p);
}
Cases where it doesn't work: the entity is detached (fetched outside a transaction, or the transaction has ended), or the transaction is @Transactional(readOnly = true), in which case Hibernate skips the flush.
In a transaction that loaded thousands of entities, dirty checking itself costs time; in a profiler you see it inside flush.
Sign up to mark studied questions and save your progress.