Tim Tim - 7 months ago 353
Java Question

How to force commit Spring - hibernate transaction safely

We are using spring and hibernate for an web application:
The application has a shopping cart where user can place items in it. in order to hold the items to be viewed between different login's the item values in the shopping cart are stored in tables. when submitting the shopping cart the items will be saved into different table were we need to generate the order number.

When we insert the values into the table to get the order number, we use to get the max order number and add +1 to it. we are using spring transaction manager and hibernate, in the code flow we get the order number and update the hibernate object to hold the order num value. when i debug, i noticed that only when the complete transaction is issued the order number entity bean is being inserted.

Issue here is when we two request is being submitted to the server at the same time, the same order number is being used, and only one request data is getting inserted. could not insert the other request value which is again a unique one.
The order num in the table is a unique one.

i noticed when debugging the persistant layer is not getting inserted into the database even after issuing session flush

session.flush()


its just updating the memory and inserting the data to db only at the end of the spring transaction . i tried explicitly issuing a commit to transaction

session.getTransaction().commit();


this inserted the values into the database immediately, but on further code flow displayed message that could not start transaction.

Any help is highly appreciated.

Added:
Oracle database i used.
There is a sequence number which is unique for that table and also the order number maps to it.

Answer

I would set the order number with a trigger which will run in the same transaction with the shopping cart insert one.

After you save the shopping cart, to see the updated order count, you'll have to call:

session.refresh(cart);

The count shouldn't be managed by Hibernate (insertable/updatable = false or @Transient).