Search code examples
hibernateconcurrentmodification

concurrent update with hibernate


Suppose user_1 and user_2 accessed an employee with id = 101, name = Rahul, accountBalance = 1500 at the same instant. so both user have employee with above mentioned values in their hand now. User_1 added a 1000 to accountBalance and updated employee. so his balance is 2500 now in the database.

And immediately after user_1 updates the employee, user_2 adds a 500 to account balance. so 500 will be added to employee's account balance which is in user_2's hand currently. so 1500+500 =2000.

But, actually it should be (1500+1000)+500 = 3000.

How this problem is handled in java with hibernate?

Do we want to check for the latest value again in the business method updateEmployee() and then add amount to that new accountBalance?

Please help me to get this situation handled in proper way. thanks and regards


Solution

  • You do that by enabling optimistic locking, using a field annotated with @Version. At each update, Hibernate will check that the version is the same in database as it is in memory, and increment the version. If the versions don't match, it will throw an exception.

    More about optimistic locking in the documentation.