• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hibernate locking strategies

 
Dave Brown
Ranch Hand
Posts: 301
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I just wanted to check something i'm unsure about, I'm writing a multi-user swing based app with hibernate and am a little unsure when it comes to locking strategy.

say for example, user Foo wants to edit a record which reflects a customers details, I envision the user clicking on a text field which at that point I want to either go into edit mode or display a message to the user..

Is the best way to "select for update" when they click on the textfield ?

Thanks
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can cause Hibernate to do a SELECT...FOR UPDATE by passing LockMode.UPGRADE to Session.get() or Session.load().

If you have already loaded the object, you can call Session.lock() to lock the object.

If you are retrieving the object using a query, you can call Query.setLockMode().
 
Chris Richardson
author
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave,

There are a couple of different ways to do this. If you are doing everything within a single database transaction then you can use database level locking as the Scott suggests.

However, the problem with this is that long transactions/holding onto database connections can limit the scalability of your application. This is especially true in web applications. Quite often a better approach is to use multiple database transactions: one to read the data and then another one to update the data (when the user saves their changes).

You then have to use application-level locking. There are two patterns: Optimistic Offline Lock, which is optimistic locking usually with a version number, across multiple transactions. See Fowler: http://www.martinfowler.com/eaaCatalog/optimisticOfflineLock.html. Alternatively, you can use the Pessimistic Offline lock pattern, where you implement an application-level lock. See http://www.martinfowler.com/eaaCatalog/pessimisticOfflineLock.html. My book describes these patterns in detail.

Chris
 
Dave Brown
Ranch Hand
Posts: 301
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, thanks Chris.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic