Background: I am using hibernate objects for database access.
inside my servlet's doGet I have:
Account account=getUserAccountHibernateObject();
doWorkOnAccount(account);
decreaseAccountBalanceAndSaveToDB(account);
Since servlet allows concurrent access, the accountBalance is really messed up sometimes. I have several questions:
- What's the best practice here? Should my thread implement SingleThreadModel to prevent concurrent access? Or synchronize everything in doGet?
Should I do the following? What's the right thing to do in hibernate?
Account account=getUserAccountHibernateObject(); doWorkOnAccount(account); account=getUserAccountHibernateObject(); decreaseAccountBalanceAndSaveToDB(account); //also synchronize this method.
Edit: tentative solution: thanks to the link provided by the answers, I think I need to span DB transaction throughout the servlet request:
beginTransaction(); try{ Account account=getUserAccountHibernateObject(); doWorkOnAccount(account); decreaseAccountBalanceAndSaveToDB(account); commitTransaction(); }catch(Exception ep){ rollBackTransaction(); }finally{ closeSession(); }
if there's any hibernate/db guru out there thing there's something wrong with this, please let me know.