在 JpaRepository 中存在 ById 返回 NullPointerException



我有一个从JpaRepository扩展的实现接口 当我使用repository.existById();并在数据库中传递不可用的 ID。

它返回NullPointerException,文档中没有任何关于NullPointer的内容。

这是一个布尔值,为什么它会返回NullPointerException

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

我的仓库

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
Boolean existsAccountByClientUsername(String username);
Account findAccountByClientUsername(String username);
}

使用 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());
}

生产代码


@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方法

private void throwIfNotFoundId(Long id) {
if (!accountRepository.existsById(id)) {
throw new IllegalArgumentException("Id not found");
}
}

你有空指针的堆栈跟踪吗?

我会说是没有正确自动连接的东西抛出了空指针。

最新更新