Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>public Long getNewInvoiceNumber() { Criteria crit = getSession().createCriteria(Numbers.class); crit.setLockMode(LockMode.PESSIMISTIC_WRITE); // LINE ADDED Numbers n = ((Numbers)crit.uniqueResult()); Long newNumber = n.getInvoiceNumber() + 1L; n.setInvoiceNumber(newNumber); getSession().update(n); // LINE ADDED return newNumber; } </code></pre> <p>You must use InnoDB if using MySQL, you should ensure Hibernate is adding the "FOR UPDATE" to the SQL generated for the <code>crit.uniqueResult()</code> part. I would also set a Java breakpoint just after (to stop execution) and manually test the same SQL query causes another client to block.</p> <p>This is more to test your SQL server is sane and your Dialect is setup correctly and basically the feature works for you.</p> <p>This forces serialization at the SQL server in the generation of the next InvoiceNumber.</p> <p>This way you never get 2 InvoiceNumber the same even if 1000 users simultaneously try to make invoices.</p> <p>NOTE: LockOptions replaces the LockMode to specify mode things about this aspect of concurrency. See the hibernate release notes for help.</p> <p>NOTE: You talked of transactions lasting minutes. While the transaction is not committed no other user can generate a new invoice number. Maybe you need to run this as a nested and separate transaction. Then you have the problem holes appearing in InvoiceNumber's if there is a failure to use the number due to some other processing error. Accountants / accounting systems don't like holes in invoice numbers, nor them being out of date sequence.</p> <p>Related MySQL documentation link <a href="https://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html</a></p>
 

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