How to log entity locking

Hi,

I am trying to switch my code to optimistic locking only.

After trying DIRTY and ALL locking types I also implemented a
Version column and sucessfully reduced the number of locks.

Anyway some parts of my code still lock a row and I would like
to understand why and how long the lock is hold.

Is there a way to “log” the locking ? Switching all hibernate logs to “TRACE” created
a lot of output but I couldn’t spot any locking.

Or is it logged by Spring / Spring Data / JPA since I am using that with hibernate ?

Thanks,
Thorsten

Locking is something that your database does. An exclusive lock is acquired when you update/delete a row for the duration of the transaction. It’s also possible to acquire an exclusive lock by using LockModeType.PESSIMISTIC_WRITE through a query. There is no logging option for this, but you can certainly look into the lock statistics of your database to understand which locks are held.

Right, I understand.
But since the number of locks I see in the lock statistics changes
between Optimistic and Pessimistic Locking I figured this must have something to
do with the code.

Has the difference something to with statements (SELECT … FOR UPDATE …) or with Transaction Isolation Levels ? Something Hibernate/JPA does must be different.

Optimistic locking is an application level mechanism, so of course you will see fewer locks on the database when you use this mechanism.

Has the difference something to with statements (SELECT … FOR UPDATE …) or with Transaction Isolation Levels ? Something Hibernate/JPA does must be different.

Since you didn’t share what kind of difference you are talking about, it’s hard to tell what could make a difference. Like I wrote, locks are acquired for update/delete statements or select ... for update statements which are run when a query requests LockModeType.PESSIMISTIC_WRITE.