After getting some sleep... and doing some more testing in the morning, I believe I have figured out my problem.
So the lock is actually taken care of within a transaction
. However, when I was testing my code, I was able to retrieve a locked row using the EntityManager.find(Class, key)
method (no locking strategy specified).
I erroneously thought that by putting a lock on a row, the row could not be read, period. However, I reread the JPA definitions of PESSIMISTIC_READ
and PESSIMISTIC_WRITE
and noticed my problem:
PESSIMISTIC_READ - The Entity is locked on the database, prevents any other transaction from acquiring a PESSIMISTIC_WRITE lock.
PESSIMISTIC_WRITE - The Entity is locked on the database, prevents any other transaction from acquiring a PESSIMISTIC_READ or PESSIMISTIC_WRITE lock.
The lock doesn't necessarily prevent all reads, it just prevents another transaction from putting a READ or WRITE lock
on the row.