-1

I have an implemented interface extends from JpaRepository when I use repository.existById(); and pass unavailable id in the database.

It returns NullPointerException, there is nothing saying anything about NullPointer in the documentation.

It's a boolean, why it return NullPointerException?

https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html?is-external=true#existsById-ID-

My repository

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

    Boolean existsAccountByClientUsername(String username);

    Account findAccountByClientUsername(String username);
}

Test code that uses exsistByID

@Test
public void givenNotAvailableId_whenGetAccountById_thenThrowIllegalArgumentException() {
    Long id = Long.MAX_VALUE;
    IllegalArgumentException exception = Assertions
             .assertThrows(IllegalArgumentException.class, () -> accountService.getAccountById(id));
    Assertions.assertEquals("Id not found", exception.getMessage());
}

production code


@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }
    public Optional<Account> getAccountById(Long id) {
        throwIfNotFoundId(id);
        return accountRepository.findById(id);
    }
}

throwIfNotFoundId method

private void throwIfNotFoundId(Long id) {
    if (!accountRepository.existsById(id)) {
        throw new IllegalArgumentException("Id not found");
    }
}
arshovon
  • 13,270
  • 9
  • 51
  • 69

1 Answers1

-2

Do you have the stack trace of the null pointer?

I would say it is something not autowired up correctly that's throwing the null pointer.