-2

I got 2 versions of the same code (i assume):

Optional<UserHolder> user = userHolderRepository.findOneByUserId(source.getId());
return user.isPresent()
    ? user.get()
    : userHolderRepository.save(new UserHolder(source.getId(), source.getLogin()));

and

UserHolder userHolder = userHolderRepository
            .findOneByUserId(source.getId())
            .orElse(userHolderRepository.save(new UserHolder(source.getId(), source.getLogin())));

        return userHolder;

I also got a Message entity with @ManyToOne userHolders.

if I call the above code to get a user holder (if exists, or create one instead), the first snippet works well while the second snippet always lead to create a second userHolder with the same id.

i think the code snippets are not behaving identical, but how should I write the Optional style code to be exactly the same as the first snippet?

Thanks!

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
David Steiman
  • 3,055
  • 2
  • 16
  • 22

1 Answers1

2

the right solution to solve this is

UserHolder userHolder = userHolderRepository
            .findOneByUserId(source.getId())
            .orElseGet(() ->userHolderRepository.save(new UserHolder(source.getId(), source.getLogin())));

        return userHolder;

because like described here, orElse is always generating the object, even if the Optional does contain a value.

Community
  • 1
  • 1
David Steiman
  • 3,055
  • 2
  • 16
  • 22