【问题标题】:existById in JpaRepository return NullPointerException [duplicate]JpaRepository 中的 existsById 返回 NullPointerException [重复]
【发布时间】:2020-10-11 06:30:07
【问题描述】:

我有一个从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");
    }
}

【问题讨论】:

  • 在帖子中为您的错误添加完整的堆栈跟踪
  • 还添加更多关于您的测试代码的信息

标签: java spring spring-boot unit-testing repository


【解决方案1】:

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

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

【讨论】:

  • 这不是答案,而是评论!
  • 不让我评论,只是想帮忙
  • 那么,请先回答您能回答的问题,从而获得声望。
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 2014-06-13
  • 2018-06-21
  • 2016-12-06
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多