JPA 中的乐观锁定是如何工作的?

Optimistic locking in JPA how does it work?

我了解什么是乐观锁定 "how it work" 但我不知道如何在 Java EE 上实现它。

我在 JPA 中有一个实体,我又添加了一个 version 列,并用 @Version 对其进行了注释。但是要有一个乐观的锁定管理我只需要@Version 注释?

这是我的 Java Class:

@Entity
public class MyClass implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
    //other variables
    @Version
    @Column(name = "version")
    private int version;
 //other code
}

在我的项目中,我使用 无状态会话 bean 来访问实体 class 并坚持更多的操作,所以我默认使用 @TransactionManagement(TransactionManagementType.CONTAINER) 来处理我的交易。

我的疑问是: 使用 @TransactionManagement(TransactionManagementType.CONTAINER)(独立什么是 @TransactionAttribute(必需、强制等))并且仅在 MyClass.java 中注释 version 变量我获得了乐观锁定管理?

来自 Pro JPA 2: Mastering the Java™ Persistence API

A couple of words of warning about version fields are in order. The first is that they are not guaranteed to be updated, either in the managed entities or the database, as part of a bulk update operation. (...) The second point worth remembering is that version fields will be automatically updated only when either the non-relationship fields or the owning foreign key relationship fields (e.g., many-to-one and one-to-one source foreign key relationships) are modified. (...) By default, JPA assumes (...) Read Committed isolation. Normal execution using version locking works with Read Committed isolation to provide additional data-consistency checks in the face of interleaved writes. Satisfying tighter locking constraints than what this locking offers requires that an additional locking strategy be used.

(强调我的)

所以,回答你的问题:不。使用 @Version 并未涵盖所有碱基。

上述附加锁定策略涉及将适当的锁定模式(OPTIMISTICOPTIMISTIC_FORCE_INCREMENT)传递给 EntityManager.lock()EntityManager.refresh()EntityManager.find()Query.setLockMode(),如适用。这里就不细说了,推荐一个follow up read(书中也有详细的讨论)。