Java – How to resolve OptimisticLockingFailureException


The code that triggers the OptimisticLockingFailureException:

public void shouldIncrementUserTotalLikesByOne() throws IllegalArgumentException, UserNotFoundException {

    User user = userService.findByEmail("");

    long numberOfLikeCount = user.getLikeCount(); 


    long numberOfUpdatedUpdatedCount = user.getLikeCount(); 


    Assert.assertEquals(numberOfUpdatedUpdatedCount, numberOfLikeCount+1);

The exception occurs when is called:

org.springframework.dao.OptimisticLockingFailureException: Optimistic lock exception on saving entity:

Best Solution

I had a problem with my model. I added @Version annotation but by mistake there was wrong type of the field and the conversion process occurred during writing to MongoDB throwing OptimisticLockingFailureException exception.

The change @Version annotated field form long type to Long class resolved my problem:


private Long version

This blog article gives more details: