java - Spring Data JPA findById() 方法返回 null 而不是 Empty Optional

标签 java spring spring-data-jpa option-type

我有一个使用 Spring Data JPA 的 findById() 方法的方法应该返回一个 Optional。但是,如果指定的 id 找不到实体,它将返回 null 而不是 Empty Optional。

 public TicketEntity findTicket(String ticket) throws EntityNotFoundException {

    Optional<TicketEntity> op = ticketEntityRepository.findById(ticket);

    TicketEntity ticketEntity = op.orElseThrow(() -> new EntityNotFoundException("ticket with the id " + ticket + " not found in the system"));

    return ticketEntity;
}

调试时发现op的值为null。 这是失败的代码段。我正在使用 Spring Data JPA 2.0.8.RELEASE。请帮忙

最佳答案

在评论中,您声明这是在具有模拟依赖项的测试中。模拟将 Spring Data JPA 完全排除在外,因为它现在只是一个由来自 Mockito 的模拟实现的代理。 .

mock 的默认行为是返回 null

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

当您使用模拟运行时,您需要指示它返回一个 Optional.empty(),否则您将得到 null

注意:您可能希望为 Mockito 创建一个改进请求,以便在 Optional 返回类型的情况下默认返回 Optional.empty .

关于java - Spring Data JPA findById() 方法返回 null 而不是 Empty Optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058898/

相关文章:

java - 来自 ModelAndView 的 View 与来自 ViewResolver 的 View

带按钮的 JavaFX-8 TableView 渲染了太多按钮?

java - 弱多吨 : ensuring there's only one object for a specific database row

java - 如何使用按钮作为 double 据类型将JTextField输入存储为变量?

spring - 从src/groovy中的类获取对spring bean的引用

java - 无法注册以 null 定义的 bean 'postRepository' 。具有该名称的 bean 已在 null 中定义

spring - HTTP 使用 RestTemplate 获取 header

java - Spring数据JPA日志记录

java - 错误: Parameter out was not defined for stored procedure

java - @ManyToMany 保存关系仅在一个方向上可用一次