thatman
thatman

Reputation: 363

Locking row while updating mysql database using hibernate

I am using ORM in Java for connecting to mysql database. In java, I have an API to update a record in db. But when I am getting multiple requests at same time, The record is updated twice with inconsistency. I can not change my entity class to add a version for optimistic lock. How can i maintain persistence without that. The code looks like this:

 public void updateRecord(String userId, Double amount) {
    User user = userRepository.findById(userId);
    double balance = user.getBalance();
    user.setBalance(balance-amount);
    userRepository.save(user);
 }

I am not sure is this where we use pessimist locks or may be @Transactional annotations. Please help. Thanks in adavance !

Upvotes: 0

Views: 1801

Answers (1)

Bohdan Petrenko
Bohdan Petrenko

Reputation: 1155

If you wanna use pessimistic locking than add to your userRepository method

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select u from User u where u.id = :id")
User findByIdAndLock(@Param("id") Integer id);

and use it instead of findById

User user = userRepository.findByIdAndLock(userId);

And also it's highly recommended to manage database transactions from the application. If you don't use @Transactional higher in method call chain than mark updateRecord with it. Like this:

@Transactional
public void updateRecord(String userId, Double amount)

Upvotes: 1

Related Questions