pilkyoon
pilkyoon

Reputation: 39

How to disable optimistic locking in Spring Data JPA

Optimistic Locking annotation does not work.

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

and @Lock annotation does not work either:

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

So, I try to call:

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?

Upvotes: 3

Views: 9960

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153690

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

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

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.

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. What is the actual problem that you are trying to solve?
  2. Do you want optimistic locking or not?
  3. Do you get a particular exception when doing the save?

Upvotes: 5

Related Questions