How to use Hibernate pessimistic locking?

To use pessimistic locking in Hibernate, you can follow these steps:

  1. Add a property in the entity class to represent the version number or lock, for example:
@Entity
public class User {
    @Id
    private Long id;
    
    // 添加版本号属性
    @Version
    private int version;
    
    // 其他属性...
}
  1. LockModeType for writing in a pessimistic manner
entityManager.find(User.class, userId, LockModeType.PESSIMISTIC_WRITE);
  1. When updating an entity object in a transaction, Hibernate will automatically add a pessimistic lock to that entity.
User user = entityManager.find(User.class, userId, LockModeType.PESSIMISTIC_WRITE);
user.setName("New Name");
// 其他更新操作...
  1. When submitting a transaction, Hibernate automatically releases the pessimistic lock.

It is important to note that a pessimistic lock is an exclusive lock that prevents other transactions from reading or modifying the entity object until the locking transaction releases the lock. Therefore, caution should be exercised when using pessimistic locks to avoid performance issues caused by lock contention.

bannerAds