Search code examples
javaspring-bootjava-8in-memory-database

Java 8 Optional.ofNullable.map producing Non static method reference error


I have a method to verify a recipient of an email.

In my code .map(Recipient::getId) produces the error :

Non static method cannot be reference from a static context.

private Long verifyRecipient(Long recipientId) throws NotFoundException {
    return Optional.ofNullable(recipientRepository.findById(recipientId))
            .map(Recipient::getId)
            .orElseThrow(()-> new NotFoundException("recipient with ID" + recipientId +
                    " was not found"));
}

Recipient class:

@Entity
public class Recipient {
    @Id
    @GeneratedValue
    private Long id;

    @NotBlank
    private String name;

    @NotBlank
    @Email
    @Column(unique = true)
    private String emailAddress;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

I am using SpringBoot and H2 in memory database.

So I also have a RecipientRepository interface:

public interface RecipientRepository extends JpaRepository<Recipient, Long> {}

Defination of the findById() method:

Optional<T> findById(ID var1);

Solution

  • The method findById() already returns an Optional<T>, so you don't need to wrap the result with additional Optional.ofNullable() in this situation.

    Actually, the line:

    Optional.ofNullable(recipientRepository.findById(recipientId));
    

    returns Optional<Optional<Recipient>>, which is redundant.

    Instead, you can just write:

    private Long verifyRecipient(Long recipientId) throws NotFoundException {
        return recipientRepository.findById(recipientId)
            .map(Recipient::getId)
            .orElseThrow(() ->
                new NotFoundException("Recipient with ID " + recipientId + " was not found"));
    }