Skip to content

Commit c039138

Browse files
committed
expand doc section on pessimistic locking
1 parent 2fd8032 commit c039138

File tree

1 file changed

+19
-2
lines changed
  • documentation/src/main/asciidoc/introduction

1 file changed

+19
-2
lines changed

documentation/src/main/asciidoc/introduction/Tuning.adoc

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,8 +1009,14 @@ Indeed, the usual practice is to avoid having transactions that span user intera
10091009
That said, there _is_ also a place for pessimistic locks, which can sometimes reduce the probability of transaction rollbacks.
10101010

10111011
Therefore, the `find()`, `lock()`, and `refresh()` methods of the session accept an optional link:{doc-javadoc-url}/org/hibernate/LockMode.html[`LockMode`].
1012-
We can also specify a `LockMode` for a query.
1013-
The lock mode can be used to request a pessimistic lock, or to customize the behavior of optimistic locking:
1012+
Here's the simplest way to execute a `select ... for update` in Hibernate:
1013+
1014+
[source,java]
1015+
Book book = session.find(Book.class, isbn, LockMode.PESSIMISTIC_WRITE);
1016+
1017+
We can also link:{doc-javadoc-url}/org/hibernate/query/SelectionQuery.html#setLockMode(jakarta.persistence.LockModeType)[specify] a `LockMode` for a query.
1018+
1019+
A lock mode can be used to request a pessimistic lock, or to customize the behavior of optimistic locking:
10141020

10151021
.Optimistic and pessimistic lock modes
10161022
[%breakable,cols="26,~"]
@@ -1048,6 +1054,17 @@ However, JPA's `LockModeType.READ` is a synonym for `OPTIMISTIC` -- it's not the
10481054
Similarly, `LockModeType.WRITE` is a synonym for `OPTIMISTIC_FORCE_INCREMENT` and is not the same as `LockMode.WRITE`.
10491055
====
10501056

1057+
A pessimistic lock request may be combined with an explicit `Timeout`.
1058+
1059+
[source,java]
1060+
session.lock(book, LockMode.PESSIMISTIC_WRITE, Timeout.seconds(2))
1061+
1062+
The interface link:{doc-javadoc-url}/org/hibernate/Timeouts.html[`Timeouts`] defines some special instances of `Timeout` which may be used to request use of link:{doc-javadoc-url}/org/hibernate/Timeouts.html#NO_WAIT[`for update nowait`] or link:{doc-javadoc-url}/org/hibernate/Timeouts.html#SKIP_LOCKED[`for update skip locked`] on databases which support these options.
1063+
1064+
[source,java]
1065+
session.lock(book, LockMode.PESSIMISTIC_WRITE, Timeouts.NO_WAIT)
1066+
1067+
10511068
[[statistics]]
10521069
=== Collecting statistics
10531070

0 commit comments

Comments
 (0)