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
?
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");
}
}