美文网首页
JPA 中的悲观锁

JPA 中的悲观锁

作者: RJ_Hwang | 来源:发表于2019-06-19 20:58 被阅读0次

    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<String, Object> 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<String, Object> 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 中的悲观锁

          本文链接:https://www.haomeiwen.com/subject/lzylqctx.html