Preventing lost updates with JPA @Version optimistic locking
Prevent lost updates in back-office admin screens using JPA @Version optimistic locking, hidden form fields, and a conflict UI that preserves unsaved edits.
Concurrent edits in back-office admin forms easily cause lost updates when two operators save the same record minutes apart. This post walks through combining JPA
@Versionoptimistic locking with a hidden form field and a conflict-handling UI that preserves unsaved drafts instead of throwing an error page.
The problem: lost updates and last write wins in admin screens
When building internal back-office systems, one of the easiest concurrency bugs to overlook is the lost update problem.
If two operators open the same article or master record in a web admin panel without concurrency control, the database simply applies last write wins. Whoever clicks Save second overwrites the first operator’s changes without a warning.
sequenceDiagram
autonumber
actor AdminA as Admin A (admin_lee)
actor AdminB as Admin B (admin_park)
participant Server as Spring Boot Server
participant DB as PostgreSQL (articles)
AdminA->>Server: 11:40:00 GET /admin/articles/1/edit
Server->>DB: SELECT * FROM articles WHERE id = 1
DB-->>Server: title: "Initial title", version: 1
Server-->>AdminA: Render edit form (version: 1)
AdminB->>Server: 11:40:10 GET /admin/articles/1/edit
Server->>DB: SELECT * FROM articles WHERE id = 1
DB-->>Server: title: "Initial title", version: 1
Server-->>AdminB: Render edit form (version: 1)
Note over AdminA,AdminB: Both admins spend a few minutes editing the body
AdminA->>Server: 11:42:15 POST /admin/articles/1/edit
Server->>DB: UPDATE articles SET title = "Admin A edit" WHERE id = 1
DB-->>Server: UPDATE 1 (success)
Server-->>AdminA: Redirect with success flash (302)
AdminB->>Server: 11:42:18 POST /admin/articles/1/edit (3s later)
Server->>DB: UPDATE articles SET title = "Admin B edit" WHERE id = 1
DB-->>Server: UPDATE 1 (overwrites A)
Server-->>AdminB: Redirect with success flash (302)
Note over DB: Admin A's edits are permanently overwritten
Suppose Admin A opens the form at 11:40, spends two minutes fixing typos and tightening a case summary, and saves at 11:42:15. Admin B opened the exact same form at 11:40:10, edited a different paragraph, and clicks Save three seconds later at 11:42:18.
PostgreSQL accepts Admin B’s UPDATE without hesitation. Admin A’s work vanishes, and you end up with confused messages in Slack asking why saved edits rolled back on their own.
Why pessimistic locking fails for web admin forms
Reaching for a database pessimistic lock (SELECT ... FOR UPDATE) makes things worse in a browser-based admin flow:
- Long user think time: An operator might open an edit form, step into a meeting, or grab coffee for 20 minutes.
- Connection pool exhaustion: Holding a database transaction open across HTTP think time drains HikariCP connections fast and can take down the whole application.
- Unnecessary contention: Two admins rarely edit the exact same record at the exact same minute. Locking every read penalizes the common case.
When contention is low and think time is high, optimistic locking is the right fit: let anyone open the form freely, and detect version conflicts at commit time.
Two-stage conflict detection and recovery UX
In demo-backend-server, I built a two-stage safety net for admin edit forms so stale submissions fail fast and never discard what the operator typed.
flowchart TD
FormReq["Admin save request (includes form.version)"] --> S1{"Stage 1: Service pre-check<br/>(entity.version == form.version?)"}
S1 -->|"Mismatch (stale form)"| FastFail["Throw BusinessException(STALE_UPDATE)<br/>Skip unnecessary UPDATE"]
S1 -->|"Match"| DBCommit{"Stage 2: DB commit<br/>(JPA @Version check)<br/>UPDATE ... WHERE version = ?"}
DBCommit -->|"UPDATE 1"| Success["Save succeeds and redirect to list"]
DBCommit -->|"UPDATE 0 (race)"| StaleEx["Throw OptimisticLockingFailureException"]
FastFail --> CatchHandler["AdminEditController shared save handler"]
StaleEx --> CatchHandler
CatchHandler --> FormRender["Re-render edit form<br/>Keep draft title/body<br/>Show conflict banner with latest editor"]
- Stage 1 — Service-level pre-check (fail-fast): Compare
form.version(captured when the form loaded) against the currentversionloaded from PostgreSQL. If another admin already saved a newer version, throwBusinessException(AdminErrorCode.STALE_UPDATE)immediately without issuing anUPDATE. - Stage 2 — Database-level atomic check (JPA
@Version): If two requests pass Stage 1 in the exact same millisecond, JPA appendsWHERE id = ? AND version = ?to theUPDATE. Only the first transaction updates the row and bumpsversion = version + 1. The second gets 0 affected rows and raisesOptimisticLockingFailureException. - Recovery UX: Redirecting to a 500 or 409 error page wipes out the operator’s draft and creates frustration. Instead, I bind the error to
BindingResult, re-render the same form with the operator’s unsaved text intact, and display a clear top banner so they can copy their changes and reload the latest version.
Adding @Version to BaseEntity
I keep shared audit columns and the optimistic lock version on a @MappedSuperclass so every editable entity inherits the same behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// src/main/kotlin/com/example/server/common/BaseEntity.kt
package com.example.server.common
import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import jakarta.persistence.Version
import java.time.Instant
import org.hibernate.annotations.ColumnDefault
import org.hibernate.annotations.SQLRestriction
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
/**
* Shared audit columns and optimistic locking version.
*/
@MappedSuperclass
@SQLRestriction("deleted_at IS NULL")
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity(
@CreatedDate
@Column(updatable = false)
var createdAt: Instant = Instant.now(),
@LastModifiedDate
var updatedAt: Instant = Instant.now(),
@CreatedBy
@Column(updatable = false)
var createdUser: String? = null,
@LastModifiedBy
var updatedUser: String? = null,
var deletedAt: Instant? = null,
/**
* Optimistic lock version. Edit forms carry this in a hidden field and compare it on save
* so stale submissions never overwrite newer edits.
*/
@Version
@ColumnDefault("0")
var version: Long = 0,
) {
val isDeleted: Boolean get() = deletedAt != null
fun delete(at: Instant = Instant.now()) {
onDelete(at)
deletedAt = at
}
protected open fun onDelete(at: Instant) {}
}
In Kotlin, declare the
@Versionproperty asvar version: Long = 0rather thanval. Hibernate mutates this field directly during flush when incrementing the version on update. New rows start at0.
Carrying version in the form DTO and Thymeleaf template
Form DTO
Add a nullable version property to the form DTO so create forms can leave it null while edit forms populate it from the loaded entity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/main/kotlin/com/example/server/admin/dto/AdminArticleForm.kt
package com.example.server.admin.dto
import com.example.server.article.domain.Article
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Size
/**
* Form DTO for creating and editing articles.
*/
class AdminArticleForm {
/** Entity version captured when the edit form loaded. */
var version: Long? = null
@field:NotBlank(message = "Please enter a title.")
@field:Size(max = 255, message = "Title must be 255 characters or fewer.")
var title: String = ""
@field:NotBlank(message = "Please enter the body content.")
var content: String = ""
var tags: String = ""
/** Used only when creating a new article. */
var judgmentId: Long? = null
fun tagList(): List<String> = tags.split(",").map { it.trim() }.filter { it.isNotEmpty() }.distinct()
companion object {
fun from(article: Article): AdminArticleForm = AdminArticleForm().apply {
version = article.version
title = article.title
content = article.content
tags = article.tags.joinToString(", ")
}
}
}
Thymeleaf template
Render version as an <input type="hidden"> on edit screens, and place a global error banner (#fields.globalErrors()) at the top of the form.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!-- src/main/resources/templates/admin/article-edit.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head th:replace="~{admin/fragments :: head(${id == null} ? 'New Article' : 'Edit Article')}"></head>
<body>
<div class="shell">
<aside th:replace="~{admin/fragments :: sidebar('articles')}"></aside>
<main class="content">
<header class="page-header">
<h1 th:text="${id == null} ? 'New Article' : 'Edit Article'">Edit Article</h1>
<span class="count mono" th:if="${id != null}" th:text="|#${id}|">#1</span>
</header>
<form class="form-panel" th:action="${id == null} ? @{/admin/articles/new} : @{/admin/articles/{id}/edit(id=${id})}" th:object="${form}" method="post" novalidate>
<!-- Top alert banner for optimistic lock conflicts or domain validation errors -->
<div th:each="err : ${#fields.globalErrors()}" class="message error" role="alert" th:text="${err}">Error</div>
<!-- Hidden optimistic lock version captured when the form loaded -->
<input type="hidden" th:field="*{version}" th:if="${id != null}">
<table class="kv" th:if="${article != null}">
<tr>
<th>Source Judgment</th>
<td class="mono" th:text="${article.caseNumber}">2024Do1234</td>
</tr>
<tr>
<th>Author</th>
<td th:text="${article.authorNickname} ?: 'System'">Author</td>
</tr>
<!-- Created / last modified audit metadata -->
<th:block th:replace="~{admin/fragments :: auditRows(${audit})}"></th:block>
</table>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" th:field="*{title}" th:errorclass="invalid" required maxlength="255">
<div class="field-error" th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Error</div>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content" th:field="*{content}" th:errorclass="invalid" class="tall" required></textarea>
<div class="field-error" th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Error</div>
</div>
<div class="actions">
<button type="submit" class="button primary">Save</button>
<a th:href="@{/admin/articles}" class="button text">Cancel</a>
</div>
</form>
</main>
</div>
</body>
</html>
Service layer: pre-check and OPTIMISTIC_FORCE_INCREMENT
Pre-checking the version
A small Kotlin extension function on BaseEntity lets every update method enforce the Stage 1 version check in one line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/main/kotlin/com/example/server/admin/application/AdminEditService.kt
package com.example.server.admin.application
import com.example.server.admin.dto.AdminArticleForm
import com.example.server.article.domain.Article
import com.example.server.article.domain.ArticleJpaRepository
import com.example.server.common.BaseEntity
import com.example.server.common.BusinessException
import jakarta.persistence.EntityManager
import jakarta.persistence.LockModeType
import org.springframework.data.repository.findByIdOrNull
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
@Service
@Transactional(readOnly = true)
class AdminEditService(
private val articleRepository: ArticleJpaRepository,
private val entityManager: EntityManager,
) {
@Transactional
fun updateArticle(id: Long, form: AdminArticleForm) {
findArticle(id).checkVersion(form.version).update(
title = form.title.trim(),
content = form.content.trim(),
tags = form.tagList(),
)
}
/**
* Stage 1 check: reject stale forms before dirty checking runs.
* Simultaneous commits are caught at commit time by JPA @Version.
*/
private fun <T : BaseEntity> T.checkVersion(formVersion: Long?): T = apply {
if (formVersion != version) {
throw BusinessException(AdminErrorCode.STALE_UPDATE)
}
}
private fun findArticle(id: Long): Article =
articleRepository.findByIdOrNull(id) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Article not found.")
}
The error codes define both stale updates and unique constraint collisions cleanly:
1
2
3
4
5
6
7
8
9
// src/main/kotlin/com/example/server/admin/application/AdminErrorCode.kt
enum class AdminErrorCode(
override val status: HttpStatus,
override val message: String,
override val code: String
) : ErrorCode {
STALE_UPDATE(HttpStatus.CONFLICT, "Another admin updated this record first. Reload to review the latest version before saving again.", "ADMIN-002"),
DATA_CONFLICT(HttpStatus.CONFLICT, "This value conflicts with an existing record. Check the active list and trash bin.", "ADMIN-006"),
}
Pitfall: forcing a version bump on child-only updates
In a one-to-many relationship, modifying only child rows or a join table does not dirty any column on the parent entity. As a result, Hibernate never issues an UPDATE against the parent table, and the parent’s @Version stays unchanged.
In my project, replacing the list of assigned judges (judges) on a Judgment left the judgments row untouched. Another operator editing the parent Judgment would never see a version conflict.
Calling entityManager.lock(judgment, LockModeType.OPTIMISTIC_FORCE_INCREMENT) forces Hibernate to increment the parent’s version column at transaction commit even when only child associations changed:
1
2
3
4
5
6
7
8
9
10
11
@Transactional
fun updateJudgment(id: Long, form: AdminJudgmentForm) {
val judgment = findJudgment(id).checkVersion(form.version)
val assignments = resolveAssignments(form)
applyJudgmentForm(judgment, form)
judgment.replaceJudges(assignments) // Modifies only the child collection
// Force a version increment on the parent row even if only assigned judges changed
entityManager.lock(judgment, LockModeType.OPTIMISTIC_FORCE_INCREMENT)
}
Controller exception handling and conflict UX
In the controller, a shared save() helper catches both Stage 1 (BusinessException) and Stage 2 (OptimisticLockingFailureException), attaches the error message to BindingResult, and re-renders the edit view with the user’s current form data intact.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// src/main/kotlin/com/example/server/admin/presentation/AdminEditController.kt
package com.example.server.admin.presentation
import com.example.server.admin.application.AdminEditService
import com.example.server.admin.application.AdminErrorCode
import com.example.server.admin.dto.AdminArticleForm
import com.example.server.common.BusinessException
import jakarta.validation.Valid
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.dao.OptimisticLockingFailureException
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.mvc.support.RedirectAttributes
@Controller
@RequestMapping("/admin")
class AdminEditController(
private val adminEditService: AdminEditService,
) {
@PostMapping("/articles/{id}/edit")
fun updateArticle(
@PathVariable id: Long,
@Valid form: AdminArticleForm,
bindingResult: BindingResult,
model: Model,
redirect: RedirectAttributes,
): String = save(
bindingResult = bindingResult,
redirect = redirect,
listPath = "/admin/articles",
message = "Article updated.",
save = { adminEditService.updateArticle(id, form) },
formView = { articleView(id, model) },
)
/**
* Runs [save] and redirects to [listPath] when validation passes.
* On conflict or validation failure, re-renders [formView] instead of an error page.
*/
private fun save(
bindingResult: BindingResult,
redirect: RedirectAttributes,
listPath: String,
message: String,
save: () -> Unit,
formView: () -> String,
): String {
if (bindingResult.hasErrors()) return formView()
try {
save()
} catch (e: BusinessException) {
// Stage 1: service pre-check detected a stale version
bindingResult.reject(e.errorCode.code, e.errorCode.message)
return formView()
} catch (e: OptimisticLockingFailureException) {
// Stage 2: two requests raced at commit time and DB @Version caught the loser
bindingResult.reject(AdminErrorCode.STALE_UPDATE.code, AdminErrorCode.STALE_UPDATE.message)
return formView()
} catch (e: DataIntegrityViolationException) {
// Concurrent insert/update hit a unique constraint after pre-check
bindingResult.reject(AdminErrorCode.DATA_CONFLICT.code, AdminErrorCode.DATA_CONFLICT.message)
return formView()
}
redirect.addFlashAttribute("message", message)
return "redirect:$listPath"
}
}
Verification: UI, SQL, and server logs
1. Conflict alert banner in the admin UI
After Admin A saves first, Admin B submits the stale form three seconds later and sees this screen:
Figure 1. Admin edit screen on conflict. Instead of redirecting to an error page, the UI preserves Admin B’s unsaved draft and shows a banner identifying the conflict and latest editor.
The banner surfaces the conflict code (ADMIN-002) alongside the latest editor (admin_lee) from the audit metadata. Admin B can copy their draft text to the clipboard, refresh to pull the latest version, and merge the changes cleanly.
2. PostgreSQL version column increment
Checking PostgreSQL right after Admin A’s commit confirms the version bump and shows what Hibernate sends over the wire:
Figure 2. PostgreSQL console output. The first commit increments version from 1 to 2, so the stale WHERE version = 1 update matches 0 rows (UPDATE 0).
Hibernate generates an UPDATE statement scoped to the expected version:
1
2
3
UPDATE articles
SET title = ?, content = ?, version = 2, updated_at = ?, updated_user = ?
WHERE id = 1 AND version = 1;
Admin A’s transaction matches version = 1, updates 1 row, and sets version = 2. Admin B’s concurrent commit still checks version = 1, gets UPDATE 0, and triggers the optimistic lock failure.
3. Spring Boot exception translation log
Server logs confirm the full translation path from Hibernate to the controller:
Figure 3. Spring Boot log output. Hibernate throws StaleObjectStateException, Spring translates it to ObjectOptimisticLockingFailureException, and the controller catches it to re-render the form.
When 0 rows are updated, Hibernate raises StaleObjectStateException, JpaTransactionManager translates it into Spring’s ObjectOptimisticLockingFailureException, and the controller’s save() helper catches it to return the form view.
Trade-offs and production checklist
Choosing a locking strategy is as much about operator UX as it is about database consistency:
| Strategy | Pros | Cons | Best fit |
|---|---|---|---|
Pessimistic lock (SELECT ... FOR UPDATE) | Immediate serialization, no retry logic needed | Holds DB connections and blocks concurrent reads/writes | Payments, inventory deduction, ticket booking |
Optimistic lock (@Version) | Zero lock wait, no connection pool drain | Requires conflict detection and manual/automatic retry | Back-office admin forms, CMS editors, low-contention CRUD |
When not to use optimistic locking: if hundreds of workers contend on the same row every second (such as a hot inventory counter or balance ledger), optimistic locking produces constant rollbacks and retry storms. Use a pessimistic lock, an atomic SQL update (SET stock = stock - 1 WHERE stock >= 1), or a distributed lock instead.
Production checklist:
- Declare
@Versionas a mutablevaron your base entity and default existing rows to0. - Pass
versionthrough a hidden form input (or anIf-Match/ETagheader for REST APIs) and validate it in the service layer before mutating fields. - Apply
LockModeType.OPTIMISTIC_FORCE_INCREMENTwhenever an edit only modifies child collections or join tables. - Catch both your domain
STALE_UPDATEexception and Spring’sOptimisticLockingFailureExceptionin the controller, preserving the user’s unsaved form fields on conflict.
References
- To specify the lock mode to be used, you can use the @Lock annotation on query methods, as shown in the following example:
</div>
- Hibernate ORM, relational persistence for idiomatic Java
</div>