Sub topic 16
Auditing and Optimistic Locking with @Version
This chapter assumes you can map entities, use repositories, and understand that changes to managed entities are flushed when a transaction commits. It covers two features that need little code: automatic audit columns and protection against lost updates.
Auditing with Spring Data
Auditing fills in "who created this row and when" fields for you. You enable it once, then annotate fields.
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@Configuration
@EnableJpaAuditing
public class AuditConfig {
}Add the entity listener and the annotated fields to the entity:
import jakarta.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.Instant;
@Entity
@Table(name = "articles")
@EntityListeners(AuditingEntityListener.class)
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@CreatedDate
@Column(nullable = false, updatable = false)
private Instant createdAt;
@LastModifiedDate
private Instant updatedAt;
@Version
private long version;
protected Article() {
}
public Article(String title) {
this.title = title;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Instant getCreatedAt() { return createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public long getVersion() { return version; }
}@CreatedDate is set when the entity is first persisted. @LastModifiedDate is set on every update. Marking createdAt as updatable = false stops accidental overwrites.
To record the user, add @CreatedBy and @LastModifiedBy fields and define a bean that implements AuditorAware<String>. Its getCurrentAuditor() method returns an Optional holding the current user name, usually read from the security context.
Optimistic locking with @Version
Suppose two users load the same article, both edit it, and both save. Without protection, the second save silently overwrites the first. That is a lost update.
Optimistic locking assumes conflicts are rare and detects them instead of blocking. A field annotated with @Version holds a counter. Hibernate adds it to every update:
update articles set title = ?, version = 1 where id = ? and version = 0If another transaction already changed the row, the where clause matches zero rows. Hibernate then throws an exception, and Spring Data translates it to ObjectOptimisticLockingFailureException.
Common errors
- Setting the version yourself. Never write to the
@Versionfield. Hibernate manages it. - Forgetting
@EnableJpaAuditing. The audit fields staynulland no error appears. Anullable = falsecolumn then fails on insert. - Using
intorlongfor@Versionand expectingnullfor new entities. Spring Data decides whether an entity is new by checking a wrapper-type version fornull. With a primitive, it falls back to checking the id. - Swallowing the exception. Catch the failure at a layer that can respond: reload and retry, or return an HTTP 409 Conflict. Do not retry inside the same transaction, because the stale entity is still in the persistence context.
Exercise
Two users open the same Article at version 3. User A saves a new title. User B then saves a different title from the stale copy. What happens, and why?
Show answer
User B's update runs with "where id = ? and version = 3", but the row is now at version 4. No row matches, so Hibernate throws an optimistic lock exception (ObjectOptimisticLockingFailureException in Spring). User B's change is not written, so A's update is not lost.