• Post Reply Bookmark Topic Watch Topic
  • New Topic

EntityManager locking issues...  RSS feed

 
Dobes Vandermeer
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to figure out how to use locking with hibernate entitymanager on glassfish. I have an object which I want to lock pessimistically, but the JPA doesn't provide any mechanism for pessimistic locking. When using hibernate it issues a select ... for update if I call EntityManager.lock(), which allows me to use pessimistic locking with Hibernate.

This sounds fine, except it turns out that there is still a race condition between when I fetch the object using EntityManager.find() and then call EntityManager.lock() to lock it, if the object's version is incremented while EntityManager.lock() waits, it will throw an OptimisticLockException and kill the transaction, forcing me to retry.

I'm feeling a bit lost - I need to perform some critical operations that cannot be rolled back by JTA - sending emails and charging credit cards - and I can't decipher how I would achieve this given my current architecture without the risk of repeating the operation.

Should I:

1. Figure out how to use the Hibernate Session directly inside a Java EE environment; this would give me access to some promising-looking methods that might help me, but I'm not sure its even possible for me to use container-managed-transactions without using hibernate-entitymanager.
2. Learn something about the JPA API's that I didn't previously know that can help solve this problem
3. Restructure everything so that it can handle the OptimisticLockException more gracefully - my only issue here is that the code might run in a timer (using TimerService) and I don't know how to restart the transaction inside of a timout.

Please help! Thanks in advance!


 
Dobes Vandermeer
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd had some luck with potential solution #1: using Session directly. It turns out that the hibernate Session is available using ((EntityManagerImpl)getEntityManager().getDelegate()).getSession().

This allows me to use hibernate's more powerful Session objects without sacrificing the convenience of container-managed transactions and dependency injection. I was so pleased I blogged about it:

http://www.dobesland.com/2009/02/07/workaround-jpa-locking-limitations-hibernate-bypassing-entitymanager-session/


 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!