@Version 为 null 时乐观锁失败

Optimistic lock failure when @Version is null

我正在编写一些代码来生成序列号。我将读取并更新数据库中的一条记录,其中包含要生成的下一个数字。因为我希望有不同的线程访问此记录,所以我只是将 @Version 标签添加到同一实体的时间戳字段,然后控制可能上升的 OptimisticLockExceptions。

此外,我的数据库中会有几条这样的记录,它们包含不同的序列号,可以根据业务创建或删除它们。

域对象如下所示:

@Entity
@Table(name="Preferences")
public class Preferences implements Serializable, DomainObject {
...
...
@Column(name="nextSerial")
private String nextSerial;

@Version
@Column(name="RefreshDate")
private Timestamp refreshDate;
...

直到这里一切正常,当共享相同数据的另一个应用程序创建首选项记录时出现问题。构建此应用程序时,@Version 列不存在,因此它将创建具有 Null 值的记录作为 refreshDate。

我知道这一点,我尝试设置 refreshDate 并更新记录,还尝试删除并重新创建记录,但无论如何,我都会得到如下异常:

org.springframework.orm.jpa.JpaOptimisticLockingFailureException: Exception [EclipseLink-5001] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.OptimisticLockException Exception Description: An attempt was made to delete the object [com.core.domain.Preferences@5e092f04], but it has no version number in the identity map.

所以我的问题是,如何从我的应用程序中处理这个问题?。在数据库中使用触发器来确保非空 @Version 是不可取的,更改其他应用程序也是不可取的。

能否使用数据库方式在创建时为 refreshDate 设置一个默认值?喜欢

VERSION BIGINT NOT NULL DEFAULT 1 -- 对于数字版本

RefreshDate TIMESTAMP NOT NULL DEFAULT now() - 适合您的情况