JPA 中的悲观锁

JPA 规范定义了 3 种类型的悲观锁:

  • PESSIMISTIC_READ – 允许获取共享锁并防止数据被更新或删除
  • PESSIMISTIC_WRITE – 允许获取独占锁,并防止读取、更新或删除数据
  • PESSIMISTIC_FORCE_INCREMENT – 类似于悲观 PESSIMISTIC_WRITE,额外增加了一个版本化实体的版本属性

都定义在 LockModeType 类内。

// find
entityManager.find(User.class, id, LockModeType.PESSIMISTIC_READ);

// query
entityManager.createQuery("from User where id = :id")
  .setParameter("id", id)
  .setLockMode(LockModeType.PESSIMISTIC_WRITE)
  .getResultList()

// named query
@NamedQuery(
  name="lockUser",
  query="select s from User s where s.id = :id",
  lockMode = PESSIMISTIC_READ
)

// Lock Scope
Map properties = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
entityManager.find(User.class, 1L, LockModeType.PESSIMISTIC_WRITE, properties);

// Setting Lock Timeout - milliseconds
Map properties = new HashMap<>(); 
map.put("javax.persistence.lock.timeout", 1000L); 
entityManager.find(User.class, 1L, LockModeType.PESSIMISTIC_READ, properties);

From Pessimistic Locking in JPA.
Last modified: May 26, 2019

你可能感兴趣的:(JPA 中的悲观锁)