Sub topic 12
Transactions and when changes are flushed
This chapter assumes you know how entities map to tables, how repositories are injected into services, and the basics of the persistence context (the set of entities a session currently tracks). Here you will see how @Transactional controls when changes reach the database.
What a transaction gives you
A transaction groups several database operations into one unit. They all succeed or none do. In Spring, @Transactional on a method opens a transaction before the method runs. It commits when the method returns normally and rolls back when it throws.
The persistence context lives as long as the transaction. Entities you load inside the method are managed. Hibernate tracks them and compares them to a snapshot taken at load time.
Dirty checking and flush
Flushing means sending pending SQL to the database. It does not commit. Hibernate flushes:
- before the transaction commits,
- before a query that might be affected by pending changes (in the default auto flush mode),
- when you call
flush()orsaveAndFlush()explicitly.
At flush time, Hibernate compares each managed entity with its snapshot. If a field differs, it issues an UPDATE. This is dirty checking. It is why the method below needs no save() call.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CatalogService {
private final BookRepository books;
public CatalogService(BookRepository books) {
this.books = books;
}
@Transactional
public void renameBook(Long id, String newTitle) {
Book book = books.findById(id).orElseThrow();
book.setTitle(newTitle); // requires a setTitle method on Book
}
}The Book class from the earlier chapter has no setTitle, so add one (for example public void setTitle(String title) { this.title = title; }) before running this. The UPDATE books SET ... WHERE id = ? runs at commit.
Repository methods are transactional too
Repository methods from SimpleJpaRepository run in their own transaction, and read methods are marked read-only. If your service method is already transactional, the repository calls join that transaction. This is the default propagation, REQUIRED.
Use @Transactional(readOnly = true) on methods that only read. It lets Hibernate skip dirty checking and lets some drivers optimize.
Common errors
- Changes silently lost. The entity was loaded outside a transaction, so it is detached. Changing it does nothing unless you call
save()inside a transaction. - Self-invocation. Calling a
@Transactionalmethod from another method of the same class bypasses the Spring proxy. No transaction starts. - Private or final methods. The proxy cannot intercept them.
- Unexpected commit of rollback-only work. By default, Spring rolls back only on unchecked exceptions. A checked exception commits unless you set
rollbackFor. - Stale reads after a bulk update. A
@ModifyingJPQL update bypasses the persistence context, so loaded entities keep old values. Use@Modifying(clearAutomatically = true).
Exercise
A service method has no @Transactional annotation. It calls books.findById(1L), changes the title with a setter, and returns without calling save(). Is the change written to the database? Why or why not?
Show answer
No. Without a surrounding transaction, the repository's own short transaction ends when findById returns, so the entity becomes detached. Dirty checking only happens for managed entities at flush. Add @Transactional to the method, or call books.save(book) inside a transaction.