How do I implement row-level locking when Spring boot uses Jpa to operate the database?

Spring boot uses jpa to operate MySQL InnoDB;
for example:

products;
id;
quantity;
;
id=3211:

I see the sql statement on the Internet is:

SET AUTOCOMMIT=0;//
BEGIN WORK;//
SELECT quantity FROM products WHERE id=3 FOR UPDATE;
UPDATE products SET quantity = "1" WHERE id=3;
COMMIT WORK;//

what if I implement this when I use Jpa? I searched the Internet and found the following implementation:

@Lock(LockModeType.PESSIMISTIC_WRITE)  
public products findById(int id);

question 1. How to use it in practice?
my idea: I first call findById (3), and then modify the quantity after, save (products), is like this? So the thing is fully submitted?
question 2. What if I don"t call save (products), after I call findById (3)?
question 3. If it is different from what I thought in question 1, how should I do it?


handwritten statements + annotations, mysql Innodb will add row-level locks to ensure the thread safety of the following statements, of course, as long as your id has an index


@Modifying
@Query("update products sc set quantity = quantity -1 where sc.id = ?")
public void UpdateById(@Param(value = "ids") String id);

it would be better to use optimistic locks in this case

corresponding sql

 update products  set quantity = quantity - :bye_count
  where id = :id and quantity=:old_value and quantity > :bye_count
 

take out the previous inventory first. if no one else modifies it at that time, it will be modified successfully, otherwise you can try again until the inventory is no longer larger than the purchase.

Menu