Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PESSIMISTIC_WRITE lock the whole table?

Just to be sure that I correctly understand how things work.

If I do em.lock(employee, LockModeType.PESSIMISTIC_WRITE); - will it block only this entity (employee) or the whole table Employees?

If it matters, I am talking about PostgreSQL.

like image 301
Andremoniy Avatar asked Mar 07 '18 08:03

Andremoniy


People also ask

What is Pessimistic_write lock?

PESSIMISTIC_WRITE allows us to obtain an exclusive lock and prevent the data from being read, updated or deleted. PESSIMISTIC_FORCE_INCREMENT works like PESSIMISTIC_WRITE, and it additionally increments a version attribute of a versioned entity.

What is the default locking in hibernate?

As seen in previous article, Hibernate, by default, follows the JDBC approach of relying on DBMS default transaction isolation level allowing to override it for a specific transaction if required.

What is optimistic and pessimistic locking?

There are two models for locking data in a database: Optimistic locking , where a record is locked only when changes are committed to the database. Pessimistic locking , where a record is locked while it is edited.


1 Answers

It should block only the entity.

PostgreSQL hibernate dialect adds for update in case of write locks: https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java#L549 (newer versions just use the same implementation)

for update is treated row-wise by PostgreSQL: https://www.postgresql.org/docs/9.5/static/explicit-locking.html

FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being locked, modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, SELECT FOR UPDATE, SELECT FOR NO KEY UPDATE, SELECT FOR SHARE or SELECT FOR KEY SHARE of these rows will be blocked until the current transaction ends; conversely, SELECT FOR UPDATE will wait for a concurrent transaction that has run any of those commands on the same row, and will then lock and return the updated row (or no row, if the row was deleted).

like image 94
Anton Malyshev Avatar answered Sep 21 '22 13:09

Anton Malyshev