如何在Spring Data JPA中禁用开放式锁定 [英] How to disable optimistic locking in Spring Data JPA

查看:176
本文介绍了如何在Spring Data JPA中禁用开放式锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乐观锁定注释不起作用.

Optimistic Locking annotation does not work.

@OptimisticLocking(type = OptimisticLockType.NONE)
public class TestEntity {
    ....
}

@Lock注释也不起作用:

public interface TestRepository<TestEntity, Long> extends JpaRepository<Version, Long> {
    @Lock(LockModeType.NONE)
    TestEntity findByName(String name);
}

因此,我尝试致电:

entityManager.refresh();

它可以工作,但这是一种解决方法.

It works, but it's a workaround.

EntityManager em = sharedEntityManagerBean.getObject();
em.refresh(testEntity, LockModeType.OPTIMISTIC);
testRepository.save(testEntity);

您能告诉我为什么乐观锁注释不起作用吗?用最新数据更新数据库行(实体)的最佳方法是什么?

Could you tell me why optimistic lock annotation does not work and what's the best way to update DB row(entity) with the latest data?

推荐答案

OptimisticLockType.NONE禁用TestEntity的默认乐观锁定机制.

The OptimisticLockType.NONE disables the default optimistic locking mechanism for the TestEntity.

但是,仅当您从带有@MappedSuperclass@Inheritance注释的基类中继承了@Version属性时,这才有用.

However, that would only be useful if you inherited the @Version property from a base class which is annotated with @MappedSuperclass or @Inheritance.

如果您不希望对该实体进行乐观锁定,则可以简单地删除@Version属性.但是,这通常是一个坏主意,因为它可能导致丢失更新.

In your case, you could simply remove the @Version property if you don't want optimistic locking for this entity. However, that's usually a bad idea since it could lead to lost updates.

也许您想使用无版本乐观锁定,可以降低由非重叠属性变更产生的冲突率.

Maybe you want to use the versionless optimistic locking which can lower the rate of conflicts generated by non-overlapping property chanages.

同样,@Lock(LockModeType.NONE)是无用的,因为默认情况下是隐含的.您也可以删除它.这仅用于获得显式逻辑或物理锁

Again, the @Lock(LockModeType.NONE) is useless since it's implied by default. You can remove that as well. That's only meant for acquiring an explicit logical or physical lock.

您得出错误的结论,认为乐观锁定正在引起您甚至没有描述的问题.

You are drawing the wrong conclusions thinking that optimistic locking is causing an issue which you didn't even describe.

因此,您需要以适当的方式提出问题,以使其清晰明了:

Therefore, you need to formulate the question in a proper manner so that it's clear:

  1. 您要解决的实际问题是什么?
  2. 您是否需要乐观锁定?
  3. 保存时是否遇到特定的异常?

这篇关于如何在Spring Data JPA中禁用开放式锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆