• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to implement a 'select for update' using EJB

 
Jag Bains
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was wondering how I could implement database locking using EJBs and JPA.
I am using glassfish and MySQL and I believe I have to set up some properties in the persistence.xml, but I don't know what these are.

It would also be useful if I could specify which entities beans need this locking strategy.

The reason for the question is that I wrote a simple ejbClient that accesses a session bean which in turn adds 1 to a column in the database table using an entity manager.
The client spawns 3 threads each try to update the same row but in there own transaction. When I run the client the different threads use the same entity and hence produce the folliwng output :



What I really need is to somehow synchronise the access to the entity beans, so that only 1 client can update it at once.

The code below is of the test client




The session bean method does the following:


I would appreciate if someone could point me in the right direction.

Thanks
 
giuseppe morreale
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use entity manager native query and call the mysql select for update.

Alternatively you can check if your persistence provider has a query hint for pessimistlocking.
 
Jag Bains
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks. Works a treat.

Is this the correct way to enforce pessimist locking?
 
giuseppe morreale
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use a persistence provider hint you lost portability across persistence provider.
If you use a native query you lost portability across dbms.

I hope that arise some specification in JSR to support pessimistic locking(like optimistic locking support).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!