Note that there are some explanatory texts on larger screens.

plurals
  1. PODecrease value of attribute by one in Hibernate
    primarykey
    data
    text
    <p>I have an <strong>InnoDB table</strong> in my <strong>MySQL</strong> 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:</p> <pre><code>UPDATE product_stock SET current_stock = current_stock -1 WHERE product_id = ?; </code></pre> <p>Now, I'm using <strong>Hibernate</strong>, so I'm updating the object ProductStock by setting the value of the currentStock attribute to "currentValue -1" like this:</p> <pre><code>instance.setCurrentStock(instance.getCurrentStock()-1); ... session.saveOrUpdate(instance); </code></pre> <p>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. <strong>e.g.</strong>, I have 100, two transactions start at the same time to sell a product and both do in code </p> <pre><code>instance.setCurrentStock(instance.getCurrentStock()-1); </code></pre> <p>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?</p> <p><strong>The question:</strong> Should/must I make an HQL statement to update the stock directly to -1 instead of updating the object's value from code?</p> <p><strong>UPDATE:</strong></p> <p>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 <strong>deadlock</strong> at database level. We are currently working on it and the answers given are being very helpful.</p> <p>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</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload