Answer a question

The code that triggers the OptimisticLockingFailureException:

@Test
public void shouldIncrementUserTotalLikesByOne() throws IllegalArgumentException, UserNotFoundException {
    databuilderService.createAll();

    User user = userService.findByEmail("abc@gmail.com");

    long numberOfLikeCount = user.getLikeCount(); 

    userService.incrementUserTotalLikesByOne(user.getId()); 

    userService.save(user);

    long numberOfUpdatedUpdatedCount = user.getLikeCount(); 

    Assert.assertNotNull(numberOfUpdatedUpdatedCount);

    Assert.assertEquals(numberOfUpdatedUpdatedCount, numberOfLikeCount+1);
}

The exception occurs when UserService.save() is called:

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

Answers

Optimistic locking exception means the object being persisted have already changed it's state in the database (some other transaction saved the object).

So, this is a domain specific problem. You have to decide what should be done.

Basically two options:

  1. Present the error to the user.

  2. Read the object from database and merge the changes. With this you should assume that you may lose the modifications done by other transactions.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐