I have an **InnoDB table** in my **MySQL** which stores the current stock of a product, whenever a product is sold (always by the unit, i.e. always -1), the stock has to be updated by doing, let's say, something like:

```
UPDATE product_stock SET current_stock = current_stock -1 WHERE product_id = ?;

```

Now, I'm using **Hibernate**, so I'm updating the object ProductStock by setting the value of the currentStock attribute to "currentValue -1" like this:

```
instance.setCurrentStock(instance.getCurrentStock()-1);
...
session.saveOrUpdate(instance);

```

Now, I'm using transactions to commit the changes, however I'm not sure what will hibernate do when multiple sells are being made at the same time, and I haven't been able to successfully replicate the problem which I think will happen, that is, the current\_stock won't be saved as current\_stock -1 but as the value i setted to the object's instance attribute. **e.g.**, I have 100, two transactions start at the same time to sell a product and both do in code 

```
instance.setCurrentStock(instance.getCurrentStock()-1); 

```

setting both the stock to 99, then the transactions end and the current stock is saved to 99 when it should have been 98, am I right?

**The question:** Should/must I make an HQL statement to update the stock directly to -1 instead of updating the object's value from code?

**UPDATE:**

I was able to replicate the error by load testing the application with many users making a purchase at the same time, but what is actually happening is not that Hibernate is saving the stock wrong, what is happening is a **deadlock** at database level. We are currently working on it and the answers given are being very helpful.

The problem I'm now facing is that handling the locks might be tricky, because the current\_stock table and specifically some rows of it might have many reads and many writes at the same time. I'll post the progress and hopefully the final solution