Stack Exchange
Springboot: How to get an entity optional property and check null?
I have a service in Springboot and I want to get an optional entity and to check if is not null to do something after.
User repository class
public interface UserRepository extends JpaRepository<UserEntity, Long> {

    Optional<UserEntity> findByLastName(String lastName);
}

Role repository class
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {
    Optional<RoleEntity> findByName(String name);
}

How can I write properly this code below?
 public UserEntityDto addRoleToUser(String username, String rolename) {
        Optional<UserEntity> usrDb = userRep.findByLastName(username);
        Optional<RoleEntity> roleDb = roleRep.findByName(rolename);
        UserEntity userEntity = usrDb.orElse(null);
        RoleEntity roleEntity = roleDb.orElse(null);
        if (userEntity != null && roleEntity != null) {
            userEntity.getRoles().add(roleEntity);
        }

        return userEntityMapper.fromUserEntity(userEntity);
    }


There's no nice way of combining optionals in situations like this.
You could possibly look at Optional.ifPresent if you like lambdas;
usrDb.ifPresent(u -> {
  roleDb.ifPresent(r -> u.getRoles().add(r));
}

Alternatively use Optional.isPresent
if (usrDb.isPresent() && roleDb.isPresent()) {
  usrDb.get().getRoles().add(roleDb.get())
}

