Sub topic 12
Transactions and when changes are flushed
This chapter assumes you know what a managed entity is, how a repository is injected, and how @Transactional appears on a Spring bean. It covers where transactions begin and end, when Hibernate sends SQL, and the errors that come from misunderstanding both.
Why the transaction matters to JPA
The persistence context (the set of entities Hibernate is tracking) lives only as long as a transaction, in the default Spring setup. Inside a transaction, entities you load are managed. Hibernate takes a snapshot of each one when it loads it. When it flushes, it compares each entity with its snapshot and issues SQL for the differences. This comparison is called dirty checking.
A flush sends pending changes to the database. A commit makes them permanent. These are separate events, and most confusion comes from mixing them up.
How @Transactional works
Spring wraps a bean annotated with @Transactional in a proxy. When a caller invokes a method on the proxy, the proxy does three things:
- It opens a transaction and binds an
EntityManagerto the current thread. - It calls your method.
- It commits if the method returns normally, or rolls back if a runtime exception escapes.
Repository methods are transactional by default. SimpleJpaRepository marks read methods as readOnly = true and write methods such as save and delete as plain @Transactional. If your service method has its own transaction, the repository calls join it. Without one, each repository call gets its own short transaction, and the entities it returned become detached when it ends.
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
// No save() call needed: the entity is managed, and the change
// is flushed to the database when the transaction commits.
}
}The Book class from earlier chapters has no setTitle method, so add one before running this. At commit, Hibernate sees that title differs from the snapshot and runs update books set title=?, published_year=?, author_id=? where id=?. By default Hibernate updates every column, not only the changed one.
When a flush happens
With the default flush mode AUTO, Hibernate flushes in three situations:
- Before the transaction commits.
- Before a JPQL or HQL query runs, if pending changes might affect its result. This keeps queries consistent with changes made earlier in the same transaction.
- When you call
flush()orsaveAndFlush()explicitly.
A flush does not end the transaction. If the transaction later rolls back, the flushed SQL is undone by the database.
Two consequences follow:
- A constraint violation often appears at commit, not at the line that caused it. A unique key violation caused by
setEmail(...)surfaces when the flush runs, possibly after your method has returned. The exception then comes from the proxy, not from your service code. - With
GenerationType.IDENTITY,saveon a new entity runs theinsertimmediately, because Hibernate needs the generated id. WithSEQUENCE, the insert is delayed until flush, which allows batching.
Rollback rules
By default Spring rolls back for unchecked exceptions (RuntimeException and Error). It does not roll back for checked exceptions. The transaction commits as normal in that case.
| Exception thrown from the method | Default result |
|---|---|
| `IllegalStateException` (unchecked) | Rollback |
| `DataIntegrityViolationException` | Rollback |
| `IOException` (checked) | Commit |
To change this, use rollbackFor:
@Transactional(rollbackFor = Exception.class)
public void importCatalog(java.nio.file.Path file) throws java.io.IOException {
// any exception, checked or not, now rolls back
}A related trap: if an inner method joined to your transaction throws a runtime exception, Spring marks the transaction rollback-only. If you catch the exception in the outer method and carry on, the commit fails with UnexpectedRollbackException.
Read-only transactions
@Transactional(readOnly = true) tells Spring and Hibernate that the method does not write. Hibernate switches the session's flush mode to MANUAL, so it skips dirty checking, which saves time and memory on large reads. The JDBC driver or database may also optimize for reading. It is a hint, not a lock, and a read-only transaction can still fail to prevent writes on some databases.
@Transactional(readOnly = true)
public java.util.List<Book> search(String text) {
return books.findByTitleContainingIgnoreCase(text);
}A common layout puts @Transactional(readOnly = true) on the service class and overrides it with plain @Transactional on write methods.
Propagation
Propagation decides what happens when a transactional method is called while a transaction already exists.
| Setting | Behavior |
|---|---|
| `REQUIRED` (default) | Join the existing transaction, or start one if none exists. |
| `REQUIRES_NEW` | Suspend the current transaction and start a separate one. |
| `SUPPORTS` | Join if one exists, otherwise run without one. |
| `MANDATORY` | Join, or throw if none exists. |
| `NEVER` | Throw if a transaction exists. |
REQUIRES_NEW suits work that must commit regardless of the outer result, such as writing an audit record. It uses a second database connection, so heavy use can exhaust the connection pool. The new transaction has its own persistence context, so it cannot see unflushed changes from the outer one.
Common errors
Self-invocation skips the proxy. The proxy only intercepts calls that come from another bean. If methodA() calls this.methodB() in the same class, the @Transactional on methodB is ignored. Move methodB to another bean.
Annotation on a method the proxy cannot intercept. By default, Spring only applies @Transactional to public methods called through the proxy. A private or final method gets no transaction.
Changes silently lost. Modifying an entity outside a transaction, or on a detached instance, never reaches the database. Call save on the detached instance inside a transaction, or reload the entity first.
LazyInitializationException. If a lazy association is touched after the transaction ended, the session is closed and the proxy cannot load. Fetch what you need inside the transaction, as covered in the fetching chapter.
Long transactions. A transaction holds a database connection. Do not call slow remote services inside one.
Bulk updates and stale entities. A @Modifying JPQL update runs directly against the database and bypasses the persistence context. Entities already loaded keep their old values. Use @Modifying(clearAutomatically = true) to clear the context after the update, and flushAutomatically = true to flush pending changes before it.
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface BookBulkRepository extends org.springframework.data.jpa.repository.JpaRepository<Book, Long> {
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query("update Book b set b.publishedYear = :year where b.id = :id")
int updateYear(@Param("id") Long id, @Param("year") int year);
}Calling this method requires an active transaction, or it throws TransactionRequiredException. Put @Transactional on the calling service method.
Exercise
A service method annotated with @Transactional loads a Book, calls setTitle, and then throws a checked IOException. Does the title change reach the database? What one attribute change would alter the outcome?
Show answer
Yes, the change is committed. Spring rolls back only on unchecked exceptions by default, so the checked IOException lets the transaction commit, and the flush at commit writes the new title. Adding rollbackFor = IOException.class (or Exception.class) to @Transactional makes the transaction roll back, so the change is not persisted.
Exercise
You call books.save(book) on a new Book with a SEQUENCE generated id, and then your method throws a unique-constraint error on the commit line, not on the save line. Why?
Show answer
With SEQUENCE, Hibernate does not run the insert at save. It queues the insert and sends it at flush time, which happens at commit. The database checks the constraint when it receives the insert, so the error appears at commit. With IDENTITY, the insert runs at save, so the error would appear there.