Sub topic 16
Auditing and optimistic locking with @Version
This chapter adds two features to entities you already know how to map: automatic audit columns (who changed a row and when) and optimistic locking (detecting that two users changed the same row). It assumes you can map entities with @Entity, you understand transactions and @Transactional, and you know how the persistence context flushes changes. Both features use extra columns that the persistence layer fills in for you.
Why these two features go together
Both features add bookkeeping columns to a table and update them whenever a row changes.
- Auditing records who created or changed a row, and when. It helps with support, compliance and debugging.
- Optimistic locking protects against lost updates. Two users load the same row, both edit it, and the second save silently overwrites the first.
Auditing is a Spring Data feature. Optimistic locking is part of JPA itself.
Auditing with Spring Data
Enable auditing
Auditing is off by default. Turn it on with @EnableJpaAuditing on a configuration class, and provide an AuditorAware bean that tells Spring who the current user is.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.util.Optional;
@Configuration
@EnableJpaAuditing
public class AuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
// Replace with the name from your security context, for example
// SecurityContextHolder.getContext().getAuthentication().getName().
return () -> Optional.of("system");
}
}@EnableJpaAuditing finds the AuditorAware bean automatically when there is exactly one. If a request has no user (a scheduled job, for instance), return Optional.empty(). The @CreatedBy and @LastModifiedBy fields are then left as they are.
Put the audit fields in a base class
Audit fields repeat on every entity, so they belong in a @MappedSuperclass. A mapped superclass is not an entity itself. Its fields become columns in each subclass's table.
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.Instant;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AuditableEntity {
@CreatedDate
@Column(nullable = false, updatable = false)
private Instant createdAt;
@LastModifiedDate
@Column(nullable = false)
private Instant updatedAt;
@CreatedBy
@Column(updatable = false)
private String createdBy;
@LastModifiedBy
private String updatedBy;
public Instant getCreatedAt() { return createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public String getCreatedBy() { return createdBy; }
public String getUpdatedBy() { return updatedBy; }
}AuditingEntityListener is a JPA lifecycle listener. Before an entity is inserted, it sets the @CreatedDate and @CreatedBy fields. Before an update, it refreshes the @LastModified... fields. Marking the creation columns updatable = false stops a stray change from rewriting history.
What counts as a modification
The listener runs when Hibernate sees a dirty entity at flush time. That has three consequences:
- Changing a managed entity inside a transaction updates
updatedAtat flush, even without asave()call. - If a flush finds no changes, no update statement runs and
updatedAtstays the same. - Bulk
@ModifyingJPQL or native updates bypass the entity lifecycle entirely. They do not touch audit fields, so set them in the query yourself.
Use Instant for timestamps unless you have a reason not to. It has no time zone ambiguity, and Spring Data auditing supports it along with LocalDateTime and the legacy date types.
Optimistic locking with @Version
The idea
Optimistic locking assumes conflicts are rare. It takes no database lock while you work. Instead, each row carries a version number, and every update says "change this row only if it still has the version I read."
Add a @Version field to an entity:
import jakarta.persistence.*;
@Entity
@Table(name = "books")
public class Book extends AuditableEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Version
private Long version;
protected Book() {
}
public Book(String title) {
this.title = title;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Long getVersion() { return version; }
}Hibernate then changes every update into a conditional one:
update books set title = ?, version = ?, updated_at = ?
where id = ? and version = ?If the statement affects zero rows, another transaction has already changed the row. Hibernate throws an exception rather than overwriting the other change.
<br>
Rules for the version field
- Supported types are
int,Integer,long,Long,short,ShortandTimestamp. A numeric type is the safe choice. - Never set or change the field yourself. The persistence provider owns it.
- Use one
@Versionfield per entity. - A wrapper type such as
Longis better thanlong. Spring Data decides whether an entity is new by checking the version field first. Anullversion means new, sosave()callspersist. With a primitivelong, it falls back to checking the identifier.
Handling the failure
Spring translates the JPA exception into ObjectOptimisticLockingFailureException. How you respond depends on the situation.
import org.springframework.dao.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookEditService {
private final BookRepository books;
public BookEditService(BookRepository books) {
this.books = books;
}
@Transactional
public void rename(Long id, long expectedVersion, String newTitle) {
Book book = books.findById(id).orElseThrow();
if (book.getVersion() != expectedVersion) {
throw new ObjectOptimisticLockingFailureException(Book.class, id);
}
book.setTitle(newTitle);
}
}This method catches the case that matters most in web applications. A user opened an edit form that showed version 3, and someone else saved before the user submitted. The version travels with the form (or in an ETag header), and you compare it on submit. The database check at flush time covers the narrow window between your own read and your commit.
For work that can safely be repeated, such as a counter update, catch the exception outside the transaction and retry:
public void renameWithRetry(BookEditService service, Long id, String title) {
for (int attempt = 1; ; attempt++) {
try {
service.renameUnconditionally(id, title);
return;
} catch (ObjectOptimisticLockingFailureException e) {
if (attempt == 3) {
throw e;
}
}
}
}Here renameUnconditionally stands for a @Transactional method that reloads the entity and applies the change. Each retry must start a new transaction and read fresh data. Retrying inside the failed transaction does not work, because its persistence context holds stale state.
<br>
Gotchas
- Bulk updates skip the version. A
@Modifyingquery does not increment@Versionunless you writeset b.version = b.version + 1yourself. Hibernate also offersupdate versionedin HQL. - Detached entities carry their version. When you
save()a detached entity (one received from a form, for example), Spring Data callsmerge. Hibernate compares the version in the object with the database and fails on a mismatch. If a DTO mapper drops the version, the check is lost, so keep it. - Version changes only when data changes. An unchanged entity produces no update and no version bump.
- Collections can bump the version. Changing the contents of an owned collection, such as
Author.books, increments the parent's version. Inverse collections (mappedBy) do not. - Forcing a version bump.
@Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT)on a repository method increments the version even when the entity itself is unchanged. Use it when a change to child rows should invalidate the parent. - Optimistic versus pessimistic. Pessimistic locking (
@Lock(LockModeType.PESSIMISTIC_WRITE)) issuesselect ... for updateand blocks other writers. Prefer it only for rows with frequent conflicts, because it holds database locks while the transaction runs.
Summary of the two features
| Feature | Purpose | Set by | Column type |
|---|---|---|---|
| `@CreatedDate`, `@LastModifiedDate` | Record when a row changed | Spring Data listener | `timestamp` |
| `@CreatedBy`, `@LastModifiedBy` | Record who changed a row | Spring Data listener, via `AuditorAware` | `varchar` or a foreign key |
| `@Version` | Detect concurrent changes | Hibernate, in the update statement | `bigint` |
Exercise
A user opens an edit form for a book showing version 5. While the user types, another user saves the same book, which raises its version to 6. The first user submits the form with a DTO that has no version field, and your service loads the book and calls setTitle inside @Transactional. Does the lost-update protection work? What should you change?
Show answer
No. The service loads the book fresh, so it reads version 6 and the update succeeds with where version = 6, overwriting the other user's change. The check only compares the version loaded in the same transaction. To fix it, include the version in the form and the DTO, and compare it with the loaded entity's version before applying the change (or set it on a detached entity that is merged). Throw an ObjectOptimisticLockingFailureException, or map it to HTTP 409, on a mismatch.
Exercise
You add a @Modifying JPQL query that sets a book's title directly in the database. Afterwards, the book's updatedAt and version are unchanged. Why, and how do you fix it?
Show answer
Bulk update queries bypass the entity lifecycle, so neither the auditing listener nor Hibernate's version handling runs. Fix it by setting the fields in the query, for example update Book b set b.title = :title, b.updatedAt = :now, b.version = b.version + 1 where b.id = :id. Alternatively, load the entity and change it so that dirty checking applies.