Sub topic 8
Transaction boundaries with @Transactional
This chapter assumes you have the BookService from the previous chapter, a working Spring Data repository, and basic knowledge of what a database transaction is: a group of operations that either all succeed or all fail.
Why the service owns the transaction
A transaction should cover one complete business operation. In this API, that operation is one service method. The controller only handles HTTP, and the repository handles single queries. The service is the only layer that knows which steps belong together.
Spring Data repository methods are already transactional on their own. If a service method makes two repository calls without its own transaction, each call commits separately. A failure in the second call would leave the first one saved.
How @Transactional works
Spring wraps a bean that has @Transactional methods in a proxy, which is an object that stands in for your service. When a controller calls the service, the call goes through the proxy. The proxy opens a transaction, runs your method, then commits. If the method throws an exception, the proxy rolls back instead.
Dirty checking in the update method
The update method never calls save. Here is the relevant part of the service, with its imports.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional
public BookResponse update(Long id, BookRequest request) {
Book book = repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(request.title());
book.setAuthor(request.author());
return BookResponse.from(book);
}
}Inside the transaction, findById returns a managed entity, meaning Hibernate tracks it. At commit, Hibernate compares the entity with its loaded state and issues an UPDATE for any differences. This is called dirty checking.
Read-only transactions
Mark query methods with @Transactional(readOnly = true), as list and get do. This tells Spring and Hibernate that no writes are expected. Hibernate can then skip dirty checking for those entities. The flag is a hint, not a security rule, and some databases enforce it while others ignore it.
Rollback rules
By default, Spring rolls back only on unchecked exceptions (RuntimeException and Error). That is why BookNotFoundException extends RuntimeException. A checked exception commits the transaction unless you opt in.
@Transactional(rollbackFor = Exception.class)
public void importBooks(List<BookRequest> requests) throws IOException {
// roll back on checked exceptions too
}Common errors
- Self-invocation. If one method in
BookServicecalls another method in the same class, the call skips the proxy. The second method's@Transactionalhas no effect. Move it to another bean, or put the annotation on the outer method. - Non-public or final methods. Proxy-based transactions need public, overridable methods. Annotations on private methods are silently ignored.
- Transactions in the controller. This holds a database connection while the response is being built and mixes HTTP and data concerns. Keep the annotation in the service.
- Lazy loading outside a transaction. With
spring.jpa.open-in-view=false, as configured earlier, touching a lazy association after the service returns throwsLazyInitializationException. Convert to a DTO inside the transaction, asBookResponse.fromdoes.
Exercise
Suppose you remove @Transactional from BookService.update (and open-in-view is false). The method still returns a BookResponse with the new title. Is the new title saved in the database? Why or why not?
Show answer
No. findById runs in its own short transaction and returns a detached entity once that transaction ends. The setters change only the Java object, and nothing flushes the change, so no UPDATE is issued. The response shows the new values but the database keeps the old ones. Adding @Transactional keeps the entity managed until commit, which lets dirty checking write the change.