0

Hello I just FIXED a bug that have blown my mind, and made me doubt my understanding of the capabilities of the Java8 Optional utility.

I have a Spring backend where I m writting some UT to some services.

I have a Test active profile with H2 in memory, every thing is tuned fine.

I m mocking test data so I can check some updating mechanism.

The mocking is handled by a MockComponent that will be injected into my test.

I m generating a User entity and since I want to use the same User every where ( simply for auditing I wanted It to be unique, create one and fetch it from database.

and since I m doing this using a generic interface I used the snippet below to achieve it

    return userRepository.findByFirstName("firstName").orElse(userRepository.saveAndFlush(user));

The issue is that This code even if By inspecting in debug mode it always rising the orElse and trying to resave even if findByFirstName is fetching data successfully

The fix below is what I m doing now and it works but MY QUESTION, Why My orElse is rised even if the Optional is not Empty ??

    Optional<User> findByFirstName = userRepository.findByFirstName("firstName");
    User orElse = findByFirstName.isPresent()?findByFirstName.get() : (userRepository.saveAndFlush(user));
    return orElse;
  • 1
    the repository object is created and wasted when we use OrElse, this is why this will always rise the save. using in this case orElseGet is better suited – Mohammed Housseyn Taleb Jun 15 '22 at 10:02
  • in other words, `userRepository.saveAndFlush(user)` must be executed before `orElse(userRepository.saveAndFlush(user))` is called - **no matter** if the `Optional` is empty or not – user16320675 Jun 15 '22 at 11:48

0 Answers0