I'm working on a web application using Spring (Java and JPA + Hibernate) and I was wondering if there is a way of locking a MYSQL table and then when another web service (or even another thread from the same application) tries to read or write the locked table it waits for it to be unlocked.
For example, imagine a use case (transaction) that needs to read a value and then increment it. There is a concurrency problem, because 2 or more threads at the same time are trying to read+write the same table.
Do I have to program it manually? Is that possible with java or using any of his libraries?
UPDATE table SET x = x + 1 WHERE x = old_value
- if the value has been updated by another transaction, your transaction will fail and you can retry. Don't reinvent the wheel.update table set field = new_value where field = old_value
) or useselect for update
.