tags:

views:

34

answers:

2

Hi

I have situation in which I read a record from a database. And if everything is ok I'll modify few properties and commit transaction.

But in situations two threads do the same, they will update the same record.

How to make it in hibernate?

+2  A: 

You can use optimistic locking: give entities a version and let it throw an exception and try again later if the version isn't the same because something else (other thread, other node in a cluster or even some independant sql script that bothers to update the version) changed the same entity. Or you can use pessimistic locking: really lock the entities in the database.

See the Transactions and Concurrency chapter in the hibernate documentation for more details.

Wouter Coekaerts
A: 

Are you sure Hibernate optimistic locking works in this scenario ? I did the following. Started my web app, put a breakpoint after the point I retrieved the record from the database, updated the database row (data fields and version number column) in the database by means of Oracle Sql Developer and committed the modification, went back to my application and resumed it from the breakpoint. I hoped to get an exception, but I didn't. Did you already tried out this scenario, and did it work for you ?

EdwinDhondt