This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi developers, I need some help with JPA entities locking.
As far as I know, locking with JPA lasts as long as the persistence context in which it is invoked.
I.e. when the persistence context ends, all entities become "detached" and all locks are released.
I am accessing entities with Stateless EJBs and without using native SQL (Oracle db is used)
I would like to lock entities even while data is displayed to users in UI components (such as JSP, servlets, ...) i.e. after peristence context end.
Right now we use Optimistic locking, but this way users are warned of concurrence errors only when they try to save documents, which is unacceptable.
Should I use stateful EJBs and extended persistence contexts?
Can anyone please shed some light?
Optimistic locking is normally recommended for web applications.
Leaving locks on your database while waiting for a web application that may disappear or go to lunch is not normally a good idea.
Since pessimistic locking uses databases locks, you need to keep the database transaction open. This does not really fit with the EJB model very well, as a SessionBean normally starts and ends a JTA transaction around the method call. You will need to manage your own transactions if you wish to keep them open across requests.
If optimistic locking is really not usable for you, you may also consider application level pessimistic locking. i.e. have a LOCKED column in your table and update this when the user wants a lock, and update it again to release the lock. It will be the application responsibility to check this lock field.