Hibernate 3
Mysql
The following code can be executed simultaneously.Is there a way to garanty that the invoice number will allways be unique?
I was trying to do this with with lockmodes, but I couldn't find a way to lock the "max(inv.nr)" result.
When I execute this code simultaneous, I end up whith non unique invoice numbers.
Code:
public static void saveInvoices(List invoices){
Session hibSession = sessionFactory.openSession();
Transaction tx = hibSession.beginTransaction();
try{
Query q = hibSession.createQuery("select max(inv.number) from Invoice as inv");
//doens't work (gives an error :invalid alias "inv")
//q.setLockMode("inv",LockMode.UPGRADE);
//
Long lastInvoiceNumber = (Long)q.uniqueResult();
Long newInvoiceNumber = lastInvoiceNumber + 1L;
for(Iterator <Invoice>it=invoices.iterator();it.hasNext();){
Invoice invoice2save = it.next();
invoice2save.setNumber(newInvoiceNumber);
hibSession.saveOrUpdate(invoice2save);
newInvoiceNumber++;
}
tx.commit();
}catch (HibernateException he) {
tx.rollback();
throw he;
}finally {
hibSession.close();
}
}
All sugestions are welcome