Sub topic 8
Transaction boundaries with @Transactional
This chapter explains where a database transaction starts and ends in the book API, and what Spring does when you annotate a method with @Transactional. It assumes you have read the earlier chapters on the JPA entity, the repository, and the service layer. You should also know what a relational transaction is (commit and rollback) and how Java annotations work.
Why transactions matter in a CRUD API
A transaction groups several database operations into one unit. Either all of them are saved (commit), or none are (rollback). A single save call on a Spring Data repository already runs in its own transaction, so a one-step CRUD API can appear to work without any annotations.
The problems start when a request needs more than one step. Updating a book means loading it, changing fields, and writing it back. An import endpoint might insert fifty books. If step 37 fails, you do not want 36 orphaned rows. Declaring the boundary in the service layer lets you control that.
Where the boundary belongs
Put @Transactional on service methods. The reasons:
- A service method matches one business operation, so it is the natural unit to commit or roll back.
- Controllers deal with HTTP. Making them transactional would keep a database connection open while JSON is being written to the client.
- Repository methods are already transactional individually, but two repository calls from a service are two separate transactions unless the service wraps them.
The BookService from the previous chapter follows this rule. Each public method is one operation and one transaction.
@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);
}This method never calls repository.save. It still persists the change, as the next sections explain.
What Spring does when you add the annotation
Spring does not change your class. It wraps your bean in a proxy, which is a generated object that has the same public methods as BookService. Other beans, such as the controller, receive the proxy instead of the real service.
When the controller calls update, the proxy does the following:
- Asks the transaction manager to begin a transaction. With JPA this opens a persistence context (Hibernate session) and gets a database connection.
- Calls your real method.
- If the method returns normally, commits. If it throws a qualifying exception, rolls back.
Dirty checking
Inside the transaction, the entity returned by findById is managed. Hibernate keeps a snapshot of its original values. At commit, it compares the entity with the snapshot and issues an UPDATE if any field differs. This is called dirty checking.
That is why update needs no save call. It is also why the annotation matters. Without @Transactional, the entity would be detached as soon as findById returned, because the repository's own transaction ends there. Your setters would then change an object that nobody tracks, and the database would stay unchanged.
Read-only transactions
list and get use @Transactional(readOnly = true). This is a hint with real effects:
- Hibernate skips dirty checking for the session, which saves memory and CPU on large result sets.
- Some JDBC drivers and databases can route the work to cheaper paths, such as read replicas.
- It documents that the method must not change data.
@Transactional(readOnly = true)
public BookResponse get(Long id) {
return repository.findById(id)
.map(BookResponse::from)
.orElseThrow(() -> new BookNotFoundException(id));
}Rollback rules
By default Spring rolls back only for unchecked exceptions (RuntimeException and its subclasses) and Error. A checked exception, such as IOException, commits the transaction as if nothing went wrong.
This default is why BookNotFoundException extends RuntimeException. It also means a thrown not-found exception rolls back, which is harmless in update because nothing has been changed yet.
The following service shows rollback across several writes. It imports many books in one transaction.
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookImportService {
private final BookRepository repository;
public BookImportService(BookRepository repository) {
this.repository = repository;
}
@Transactional
public int importBooks(List<BookRequest> requests) {
for (BookRequest request : requests) {
if ("untitled".equalsIgnoreCase(request.title())) {
throw new IllegalArgumentException("Rejected title: " + request.title());
}
repository.save(new Book(request.title(), request.author()));
}
return requests.size();
}
}If the third request has the title untitled, the first two inserts are rolled back. The IllegalArgumentException is unchecked, so no extra configuration is needed.
For checked exceptions, name them explicitly:
@Transactional(rollbackFor = Exception.class)
public void importFromFile(Path file) throws IOException {
// parsing may throw IOException, which now also triggers a rollback
}Common attributes
| Attribute | Default | Purpose |
|---|---|---|
| `readOnly` | `false` | Marks the transaction as read-only, which allows optimizations |
| `rollbackFor` | unchecked exceptions | Adds exception types that cause a rollback |
| `noRollbackFor` | none | Exception types that should commit anyway |
| `propagation` | `REQUIRED` | How the method behaves when a transaction already exists |
| `isolation` | database default | Visibility of concurrent changes |
| `timeout` | none | Seconds before the transaction is marked for rollback |
REQUIRED is the right choice for nearly all CRUD code. If a transaction is already active, the method joins it. Otherwise it starts a new one. So if importBooks called another transactional service method, both would share one transaction and one commit.
REQUIRES_NEW suspends the current transaction and starts an independent one. Use it rarely, for example to write an audit record that must survive a rollback of the main work. It uses a second connection, so overusing it can exhaust the connection pool.
Gotchas caused by proxies
Because the behavior lives in a proxy, it applies only to calls that go through the proxy.
- Self-invocation. If
importBookscalledthis.createOne(...)andcreateOnehad@Transactional(propagation = REQUIRES_NEW), the annotation oncreateOnewould be ignored. The call never leaves the real object. Move the method to another bean, or restructure so one transaction is enough. - Non-public methods. Spring's default proxy-based setup applies the annotation to public methods. Annotating a private or package-private method has no effect.
- Final classes and methods. CGLIB proxies subclass your class, so
finalprevents interception. Spring Boot handles the usual cases, but keep service classes non-final. - Swallowed exceptions. If you catch the exception inside the method and do not rethrow it, the proxy sees a normal return and commits.
- Wrong annotation. Prefer
org.springframework.transaction.annotation.Transactional. Thejakarta.transaction.Transactionalannotation also works, but it lacksreadOnlyand has different rollback defaults, so mixing the two causes confusion.
Transactions and lazy loading
The earlier configuration set spring.jpa.open-in-view=false. With the default true, Spring keeps the persistence context open for the whole web request, so a controller or JSON serializer can lazily load a relationship after the service returns. That hides queries outside any transaction boundary and holds a connection longer than needed.
With it disabled, lazy associations must be loaded inside the transaction. The BookResponse.from(book) call inside the service is an example. It copies the data into a record before the proxy commits and returns. Because Book has no relationships yet, you will not notice a difference now. The setting forces the right habit before you add @OneToMany fields, where reading an uninitialized collection outside a transaction throws LazyInitializationException.
Checking that a transaction is active
When you doubt that a method is transactional, enable Spring's transaction logging in application.properties:
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUGThe log shows "Getting transaction for" and "Completing transaction for" lines with the method name. If a call is missing from the log, it did not go through the proxy.
Exercise
A developer writes a @Transactional(readOnly = true) method named rename(Long id, String title) that loads a book with findById and calls setTitle. The method returns without error, but the title in the database does not change. Give the cause and the fix.
Show answer
A read-only transaction tells Hibernate not to flush changes, so dirty checking never produces an UPDATE. The fix is to use plain @Transactional (read-write) on the method, since it modifies data. Keep readOnly = true only on methods such as get and list.
Exercise
BookImportService.importFromFile is annotated @Transactional and throws IOException after saving two books. Does the transaction roll back, and how do you change that?
Show answer
No. IOException is a checked exception, and Spring rolls back only for unchecked exceptions by default, so the two saved books are committed. Add rollbackFor = IOException.class (or Exception.class) to the annotation so the transaction rolls back.