Video in progress
`save()` is never called in this method, but the price still changes in the database. Why?
@Transactional
public void applyDiscount(Long id) {
Product p = productRepository.findById(id).orElseThrow();
p.setPrice(p.getPrice().multiply(new BigDecimal("0.9")));
// no save()
}
The entity returned by findById is managed. At the end of the transaction Hibernate runs dirty checking: it sees the changed field and sends the UPDATE itself. save() isn't needed here at all.
📖 Answer
If an entity was loaded inside a persistence context, it is considered managed. When it's loaded, Hibernate takes a copy (a snapshot) of its fields. On flush (usually just before commit) it compares the current values to that copy and writes an UPDATE if they differ.
So the sequence in this code is:
SELECT ... FROM product WHERE id = ?setPrice: for now only the Java object changed.- The method ends, Spring is about to commit, and Hibernate flushes.
UPDATE product SET price = ? ... WHERE id = ?
Juniors often think "I didn't call save, so it won't be saved", and then wonder "why did the value in the database change?" For example, they calculate a price just for display and write it onto the entity itself, and it ends up in the database.
If the change must not reach the database: do the calculation in a DTO, or use @Transactional(readOnly = true) (in Spring, Hibernate doesn't flush then), or detach the entity.
Sign up to mark studied questions and save your progress.